简体   繁体   English

JavaScript正则表达式查找以“.js”结尾而不是“-min.js”的字符串

[英]JavaScript Regex to find string that ends in “.js” but not “-min.js”

As the title states: Can any one help me figure out how to write a JavaScript regex expression that matches a string that end in ".js" but fails when given a string that ends in "-min.js". 正如标题所述:任何人都可以帮我弄清楚如何编写一个JavaScript结果表达式,该表达式匹配以“.js”结尾的字符串,但在给定以“-min.js”结尾的字符串时失败。

Examples: 例子:

hello.js -> match hello.js - >匹配

hellomin.js -> match hellomin.js - >匹配

hello-min.js -> no match hello-min.js - >不匹配

hello-min-hello.js -> match hello-min-hello.js - >匹配

Thanks! 谢谢!

Use negative lookahead: 使用否定前瞻:

(?!-min)[\\w-]{4}\\.js$

Update 更新

This will also work for less than 4 characters before the .js : 这也适用于.js之前少于4个字符:

(?:(?!-min)[\\w-]{4}|^[\\w-]{1,3})\\.js$

使用基于前一个问题的伪反转匹配:

^((?!-min\.).)*\.js$

Since JS does not support negative lookbehind, lets use negative lookahead! 由于JS不支持负面的lookbehind,让我们使用负向前瞻!

var str = 'asset/34534534/jquery.test-min.js',
    reversed = str.split('').reverse().join('');

// And now test it
/^sj\.(?!nim-)/.test(reversed); // will give you false if str has min.js at the end

Funny, right? 好笑,对吗?

I have extended @robinCTS's regex to match file paths with more than one dot (for example with version number at the end of filename) and also a string that ends in ".min.js": 我扩展了@ robinCTS的正则表达式以匹配具有多个点的文件路径(例如,文件名末尾的版本号)以及以“.min.js”结尾的字符串:

(?:(?!(-|\.)min)[\w\.-]{4}|^[\w\.-]{1,3})\.js$

Examples: 例子:

  • hello.js -> match hello.js - >匹配
  • hellomin.js -> match hellomin.js - >匹配
  • hellomin-2.4.3.js -> match hellomin-2.4.3.js - >匹配
  • hello-min-hello.js -> match hello-min-hello.js - >匹配
  • hello-min.js -> no match hello-min.js - >不匹配
  • hello.min.js -> no match hello.min.js - >不匹配
  • hellomin-2.4.3-min.js -> no match hellomin-2.4.3-min.js - >不匹配
  • hellomin-2.4.3.min.js -> no match hellomin-2.4.3.min.js - >不匹配

You can use negative lookbehind : 你可以使用负面的lookbehind:

(?<!-min)\.js$

Example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM