gpt4 book ai didi

javascript - 正则表达式匹配除以特殊字符开头和结尾的所有单词

转载 作者:行者123 更新时间:2023-11-29 19:37:06 24 4
gpt4 key购买 nike

我正在为 Javascript 的正则表达式苦苦挣扎。

这是一个字符串,我想从中匹配除前缀为\+\s 和后缀为\s\+ 的所有单词:

this-is my + crappy + example

正则表达式应该匹配:

this-is my + crappy + example

匹配 1:这是

匹配 2:我的

匹配 3:示例

最佳答案

您可以在上下文中使用交替运算符将要排除的内容放在左侧,(说把它扔掉,它是垃圾)并将要匹配的内容放在左侧的捕获组中右侧。

\+[^+]+\+|([\w-]+)

示例:

var re = /\+[^+]+\+|([\w-]+)/g,
s = "this-is my + crappy + example",
match,
results = [];

while (match = re.exec(s)) {
results.push(match[1]);
}

console.log(results.filter(Boolean)) //=> [ 'this-is', 'my', 'example' ]

或者,您可以在 + 字符之间进行替换,然后匹配您的单词。

var s = 'this-is my + crappy + example',
r = s.replace(/\+[^+]*\+/g, '').match(/[\w-]+/g)

console.log(r) //=> [ 'this-is', 'my', 'example' ]

关于javascript - 正则表达式匹配除以特殊字符开头和结尾的所有单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24845116/

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