gpt4 book ai didi

javascript - 如何在 JavaScript 中将字符串与连字符匹配?

转载 作者:行者123 更新时间:2023-11-30 19:12:19 25 4
gpt4 key购买 nike

我想匹配具有以下形式的 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 个 hypens 时有效,但是,在我的情况下,hypens 的数量可以是任意的。如何让我的正则表达式适用于任意数量的连字符?

最佳答案

你可以使用

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

参见 regex demo

详情

  • \/ - / 字符
  • ([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);
if (m) {
console.log(m[1]);
}

关于javascript - 如何在 JavaScript 中将字符串与连字符匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58354414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com