Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中将字符串与hypens匹配?_Javascript_Regex - Fatal编程技术网

如何在JavaScript中将字符串与hypens匹配?

如何在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

我想匹配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);
return (match && match.length) ? match[0] : null;
然而,这只在有2个催眠的情况下有效,然而,在我的例子中,催眠的数量可以是任意的。如何使我的正则表达式适用于任意数量的hypen?

您可以使用

/\/([a-z]+(?:-[a-z]+)*-[0-9]+)(?:\/|$)/i

详细信息

  • \/
    -a
    /
    字符
  • ([a-z]+(?:-[a-z]*)*-[0-9]+)
    -捕获组1:
    • [a-z]+
      -1+ASCII字母
    • (?:-[a-z]+)*
      -0+次出现的
      -
      后跟1+个ASCII字母
  • (?:\/|$)
    -要么
    /
    ,要么字符串结束
如果可以有任何单词字符,而不仅仅是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噢,谢谢,我刚做了。