正则表达式匹配目录后跟点

时间:2018-05-22 02:58:25

标签: javascript regex

是否有一个JavaScript正则表达式可以匹配一个后跟一个点的目录?基本上我想匹配一个文件,但不匹配目录,如:

/foo/bar/baz # does not match
/foo/bar/baz.js # matches
/foo/bar/baz.js/foo # does not match

可能吗?

6 个答案:

答案 0 :(得分:1)

您可以尝试以下功能

function check(path) {
  return path.split('/').pop().indexOf('.') > -1;
}

console.log(check('/foo/bar/baz.js')); //true
console.log(check('/foo/bar/baz')); //false
console.log(check('/foo/bar/baz.js/foo')); //false

答案 1 :(得分:1)

我虽然有这样的事情:

^ start of the string
\/? start with an optional slash
()+ a group that can repeat any amount
    [^\/]+ anything thats not a slash repeated any amount
    \/ a slash
then, the final bit must b
[^\/.]+ any non slash, non dot character, repeat any times
a single dot
[^\/.]+ any non slash, non dot character, repeat any times
$ end of string

故障:

{{1}}

答案 2 :(得分:1)

这是一种可能性:

/\.(\w)*$/g

(警告:未经测试)

答案 3 :(得分:1)

试试这个:

const isAFileInDirectory = str => /[^\.]\.[^\.\/]+$/.test(str);

console.log(isAFileInDirectory('/foo/bar/baz'));
console.log(isAFileInDirectory('/foo/bar/baz.js'));
console.log(isAFileInDirectory('/foo/bar/baz.js/foo'));

答案 4 :(得分:1)

以下是我使用的内容:/^[^\.]+\.[^/\.]+$/gi

console.log(/^[^\.]+\.[^/\.]+$/gi.test('/foo/bar/baz'));
console.log(/^[^\.]+\.[^/\.]+$/gi.test('/foo/bar/baz.js'));
console.log(/^[^\.]+\.[^/\.]+$/gi.test('/foo/bar/baz.js/foo'));

答案 5 :(得分:0)

你可以试试这个:

/^.*\/(?=\w+\.\w+)[^/]+$/

它将匹配/,然后它对\w\.\w形式的字符串(即文件名)进行正向预测,但只有在没有{{1}时才匹配在文件名之后。贪婪的/确保它在文件名之前匹配最后的.*

Demo