如何在JavaScript中将字符串与hypens匹配?
我想匹配URL中具有以下形式的某些部分:如何在JavaScript中将字符串与hypens匹配?,javascript,regex,Javascript,Regex,我想匹配URL中具有以下形式的某些部分: http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath 更准确地说,我只想匹配由所有催眠组成并以数字结尾的部分。因此,我想提取上述URL中的部分this-is-composed-of-hypens-3144。我有这样的想法: const re = /[a-z]*-[a-z]*-[0-9]*/gis; const match = re.exec(url); ret
http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath
更准确地说,我只想匹配由所有催眠组成并以数字结尾的部分。因此,我想提取上述URL中的部分this-is-composed-of-hypens-3144
。我有这样的想法:
const re = /[a-z]*-[a-z]*-[0-9]*/gis;
const match = re.exec(url);
return (match && match.length) ? match[0] : null;
然而,这只在有2个催眠的情况下有效,然而,在我的例子中,催眠的数量可以是任意的。如何使我的正则表达式适用于任意数量的hypen?您可以使用
/\/([a-z]+(?:-[a-z]+)*-[0-9]+)(?:\/|$)/i
见
详细信息
-a\/
字符/
-捕获组1:([a-z]+(?:-[a-z]*)*-[0-9]+)
-1+ASCII字母[a-z]+
-0+次出现的(?:-[a-z]+)*
后跟1+个ASCII字母-
-要么(?:\/|$)
,要么字符串结束/
[a-z]
替换为\w
var s=”http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath";
var m=s.match(/\/([a-z]+(?:-[a-z]+)*-[0-9]+)(?:\/$)/i);
如果(m){
console.log(m[1]);
}
是否只有最后一部分才有数字?删除URL的第二段不是更好吗?第一个是/somepath
第二个是/this-is-composed-of-hypens-3144
/\/([a-z]+(?:-[a-z]*)*-[0-9]+(?=\/$)/i代码>?看@VLAZ它并不总是在第二个segment@WiktorStribi噢,谢谢,我刚做了。