如何獲得JavaScript中的正則表達式中最後2個斜槓之間的字符串? 例如:獲取最後2 /之間的字符串在JavaScript中的正則表達式
stackoverflow.com/questions/ask/index.html => "ask"
http://regexr.com/foo.html?q=bar => "regexr.com"
https://www.w3schools.com/icons/default.asp => "icons"
如何獲得JavaScript中的正則表達式中最後2個斜槓之間的字符串? 例如:獲取最後2 /之間的字符串在JavaScript中的正則表達式
stackoverflow.com/questions/ask/index.html => "ask"
http://regexr.com/foo.html?q=bar => "regexr.com"
https://www.w3schools.com/icons/default.asp => "icons"
您可以使用/\/([^/]+)\/[^/]*$/
; [^/]*$
匹配一切最後一個斜線,\/([^/]+)\/
最後兩條斜線匹配之後,那麼你可以捕捉什麼介於兩者之間並解:
var samples = ["stackoverflow.com/questions/ask/index.html",
"http://regexr.com/foo.html?q=bar",
"https://www.w3schools.com/icons/default.asp"]
console.log(
samples.map(s => s.match(/\/([^/]+)\/[^/]*$/)[1])
)
您可以通過使用split()
解決這個問題。拆分後
let a = 'stackoverflow.com/questions/ask/index.html';
let b = 'http://regexr.com/foo.html?q=bar';
let c = 'https://www.w3schools.com/icons/default.asp';
a = a.split('/')
b = b.split('/')
c = c.split('/')
索引()
console.log(a[a.length-2])
console.log(b[b.length-2])
console.log(c[c.length-2])
我個人不建議使用正則表達式。因爲它是很難維持
我相信會做:
[^\/]+(?=\/[^\/]*$)
[^\/]+
這比/
以外的所有字符相匹配。將此(?=\/[^\/]*$)
放入序列中查找最後/
之前的模式。
var urls = [
"stackoverflow.com/questions/ask/index.html",
"http://regexr.com/foo.html?q=bar",
"https://www.w3schools.com/icons/default.asp"
];
urls.forEach(url => console.log(url.match(/[^\/]+(?=\/[^\/]*$)/)[0]));
您可以使用(?=[^/]*\/[^/]*$)(.*?)(?=\/[^/]*$)
。你可以在這裏測試它:https://www.regexpal.com/
正則表達式的格式是:(第二個最後一個斜槓的正向前視)(。*?)(正向最後一個斜槓的向前)。
(.*?)
對於斜線之間的內容很懶。
引用: