正则表达式检查文件是否有任何扩展名

ole*_*sii 2 regex file-extension path

我正在寻找一个正则表达式来测试文件是否有任何扩展名.我将其定义为:如果在最后一个"."之后没有斜杠,则file具有扩展名..斜杠总是反斜杠.

我从这个正则表达式开始

.*\..*[^\\]
Run Code Online (Sandbox Code Playgroud)

这转化为

.*          Any char, any number of repetitions 
\.          Literal .
.*          Any char, any number of repetitions 
[^\\]       Any char that is NOT in a class of [single slash]
Run Code Online (Sandbox Code Playgroud)

这是我的测试数据(不包括##,这是我的评论)

\path\foo.txt            ## I only want to capture this line
\pa.th\foo               ## But my regex also captures this line <-- PROBLEM HERE
\path\foo                ## This line is correctly filtered out
Run Code Online (Sandbox Code Playgroud)

这样做的正则表达式是什么?

Bla*_*ear 7

您的解决方案几乎正确.用这个:

^.*\.[^\\]+$
Run Code Online (Sandbox Code Playgroud)

在rubular的样本.


Bil*_*ell 5

我不会在这里使用正则表达式。我会split继续/.

var path = '\some\path\foo\bar.htm',
    hasExtension = path.split('\').pop().split('.').length > 1;

if (hasExtension) console.log('Weee!');
Run Code Online (Sandbox Code Playgroud)

这里有一个更简单的函数来检查它。

const hasExtension = path => {
    const lastDotIndex = path.lastIndexOf('.')
    return lastDotIndex > 1 && path.length - 1 > lastDotIndex
}

if (hasExtension(path)) console.log('Sweet')
Run Code Online (Sandbox Code Playgroud)