获取最后2 /之间的字符串在JavaScript中的正则表达式
问题描述:
如何获得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/
正则表达式的格式是:(第二个最后一个斜杠的正向前视)(。*?)(正向最后一个斜杠的向前)。
(.*?)
对于斜线之间的内容很懒。
引用: