简体   繁体   English

正则表达式模式,用于匹配URL扩展名

[英]regex pattern for match with extension of URL

I have these sample URLs: 我有以下示例URL:

1) example.com/foo.js
2) example.com/foo.js?
3) example.com/foo.js?bar

4) example.com/foo.jsbar
5) example.com/foo.js/bar

I want regex js for match with 1, 2, 3 and don't match with 4, 5. with extension. 我想要正则表达式js与1,2,3匹配,并且不与4,5,具有扩展名的匹配。

I use this pattern in LiveHTTP headers add-on firefox . 我在LiveHTTP标头附加组件firefox中使用了这种模式。

Firstly I write this: 首先,我这样写:

.js$

This just point to the 1. 这只是指向1。

And this: 和这个:

.js\?

Point to the 2, 3. 指向2,3。

And this: 和这个:

.js\??$

Point to 1, 2. 指向1、2。

So finally I write this: 所以最后我这样写:

.js$|.js\?

This works well. 这很好。

Test online: https://regex101.com/r/BU5IqH/2 在线测试: https//regex101.com/r/BU5IqH/2

Now my question is how can I have a regex with use once .js string in the pattern? 现在我的问题是,如何在模式中使用一次使用.js字符串的正则表达式?

Brief 简要

My answer is slower than @Wiktor's answer , but more readable. 我的答案比@Wiktor的答案要慢,但可读性更高。 That being said: 话虽如此:

  • If readability is your main concern use my answer. 如果您主要关注可读性 ,请使用我的答案。
  • If performance is your main concern use @Wiktor's answer . 如果您最关注性能 ,请使用@Wiktor的答案

Code

See regex in use here 查看正则表达式在这里使用

\.js(?:\?|$)

In the comments below your question you said I could remove ?: , so in that case the regex would be \\.js(\\?|$) 在您的问题下面的注释中,您说我可以删除?: ,因此在这种情况下,正则表达式为\\.js(\\?|$)

Usage 用法

 var a = [ 'example.com/foo.js', 'example.com/foo.js?', 'example.com/foo.js?bar', 'example.com/foo.jsbar', 'example.com/foo.js/bar', 'asasa.com/asasas.css', 'asasa.com/asasas.gif']; var r = /\\.js(?:\\?|$)/; a.forEach(function(s) { console.log(s + ': ' + r.test(s)); }); 


Explanation 说明

  • \\.js Match .js literally \\.js .js从字面上匹配.js
  • (?:\\?|$) Match either of the following (?:\\?|$)匹配以下任一
    • \\? Match the question mark character ? 匹配问号字符? literally 从字面上看
    • $ Assert position at the end of the line $在行尾声明位置

You want to match .js that is followed with ? 您想匹配后跟的.js ? or end of string. 或字符串结尾。

Use 采用

/\.js(?![^?])/

Details 细节

  • \\. - a dot -一个点
  • js - a js substring js - js子字符串
  • (?![^?]) - that is not followed with a char other than ? (?![^?]) -除?以外没有其他字符 (so, there can only be a match if there is ? or end of string) immediately to the right of the current location. (因此,只有在存在?或字符串结尾的情况下才有匹配项)在当前位置的右边。

See the JS demo: 参见JS演示:

 var strs = [ 'example.com/foo.js', 'example.com/foo.js?', 'example.com/foo.js?bar', 'example.com/foo.jsbar', 'example.com/foo.js/bar']; var rx = /\\.js(?![^?])/; for (var s of strs) { console.log(s, "=>", rx.test(s)); } 

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

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