【问题标题】:Javascript regular expression that matches files with particular extension except for some specific filenamesJavascript 正则表达式匹配具有特定扩展名的文件,但某些特定文件名除外
【发布时间】:2017-09-25 10:22:14
【问题描述】:

我希望它匹配所有指向 css 文件的路径,除了某些特定的文件名 (file.css):

var re = /.../;
console.log(re.test('/path/to/file.css')); // false
console.log(re.test('/path/to/file.js')); // false
console.log(re.test('/path/to/file2.js')); // false
console.log(re.test('/path/to/e.css')); // true
console.log(re.test('/path/to/other-file.css')); // true
console.log(re.test('/path/to/file2.css')); // true

那如果我也想排除asdfg.css呢?

附:问题是关于无法编写代码,只能指定正则表达式的情况。

【问题讨论】:

标签: javascript regex negative-lookbehind


【解决方案1】:

我想我会这样做:

var re = /\/(?!(file|asdfg)\.css$)[^\/]*\.css$/;

console.log(re.test('/path/to/file.css')); // false
console.log(re.test('/path/to/file.js')); // false
console.log(re.test('/path/to/file2.js')); // false
console.log(re.test('/path/to/e.css')); // true
console.log(re.test('/path/to/other-file.css')); // true
console.log(re.test('/path/to/file2.css')); // true
console.log(re.test('/path/to/asdfg.css')); // false
console.log(re.test('/path/to/file/file2.css')); // true
console.log(re.test('/path/to/file.css/file2.css')); // true

我认为这更具可读性,因为排除列表是一​​个简单的替换,可以轻松扩展以包含其他文件,而无需考虑其他因素(例如它们的长度)。

正则表达式首先匹配路径中的最后一个/(从技术上讲,它匹配任何斜杠,但后面的代码确保不会有另一个斜杠)。然后,它使用否定的前瞻检查是否没有匹配排除的文件。前瞻需要锚定到字​​符串的末尾,以确保它不会过于慷慨地排除。在前瞻之后,它只是消耗尽可能多的“非斜杠”(即文件名),然后检查所有内容是否以 .css 结尾。

【讨论】:

  • 我在这里唯一能说的就是在这里使用+ 而不是* 更有意义。但这没什么大不了的。
【解决方案2】:

这是我的解决方案:

var re = /\/(.{0,3}|(?!file).{4}|[^/]{5,})\.css$/;
console.log(re.test('/path/to/file.css')); // false
console.log(re.test('/path/to/file.js')); // false
console.log(re.test('/path/to/e.css')); // true
console.log(re.test('/path/to/other-file.css')); // true

对于两个文件:

var re = /\/(.{0,3}|(?!file).{4}|(?!asdfg).{5}|[^/]{6,})\.css$/;
console.log(re.test('/path/to/file.css')); // false
console.log(re.test('/path/to/asdfg.css')); // false
console.log(re.test('/path/to/file.js')); // false
console.log(re.test('/path/to/e.css')); // true
console.log(re.test('/path/to/other-file.css')); // true

如果您知道任何更好/可读的方法,请随时发布您的答案。

【讨论】:

  • 你为什么把这个作为答案?只需编辑您的原始问题。
  • @Keith 因为它回答了我的问题。那有什么问题呢?随时发布您的答案。如果更好,我会接受。
  • 您知道每个人都可以看到您的个人资料,而我只是快速浏览了一下。您似乎经常这样做,然后将您自己的答案标记为已接受的答案。坦率地说,我觉得你的所作所为有点令人反感。我什至懒得回答,因为即使人们试图帮助你,你仍然接受了你自己的回答。无论如何,这取决于你,人们会根据你的优点来评判你,而不是你名字旁边的号码。
  • @Keith 随时向我展示我接受更差答案的问题,我要么解释你错的原因,要么接受其他答案(这是可能的,犯错是人为的)。关于“试图帮助我的人”,如果这是他们主要关心的问题,我很同情他们。我不需要帮助。在问这个问题之前我有一个解决方案。但我希望现在我们有一个更好的解决方案,有人会从中受益。然后,我不能老实说,我不在乎我名字旁边的 No.。但除了提出我关心的问题之外,我没有做任何事情来增加它。
  • I pity them, 就是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多