[英]regex pattern for match with extension of URL
我有以下示例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
我想要正則表達式js與1,2,3匹配,並且不與4,5,具有擴展名的匹配。
我在LiveHTTP標頭附加組件firefox中使用了這種模式。
首先,我這樣寫:
.js$
這只是指向1。
和這個:
.js\?
指向2,3。
和這個:
.js\??$
指向1、2。
所以最后我這樣寫:
.js$|.js\?
這很好。
在線測試: https : //regex101.com/r/BU5IqH/2
現在我的問題是,如何在模式中使用一次使用.js
字符串的正則表達式?
我的答案比@Wiktor的答案要慢,但可讀性更高。 話雖如此:
\.js(?:\?|$)
在您的問題下面的注釋中,您說我可以刪除?:
,因此在這種情況下,正則表達式為\\.js(\\?|$)
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)); });
\\.js
.js
從字面上匹配.js
(?:\\?|$)
匹配以下任一
\\?
匹配問號字符?
從字面上看 $
在行尾聲明位置 您想匹配后跟的.js
?
或字符串結尾。
采用
/\.js(?![^?])/
細節
\\.
-一個點 js
- js
子字符串 (?![^?])
-除?
以外沒有其他字符 (因此,只有在存在?
或字符串結尾的情況下才有匹配項)在當前位置的右邊。 參見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.