gpt4 book ai didi

javascript - 在 JavaScript 中匹配一个单词而不匹配另一个单词的正则表达式

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

我想匹配包含字符串 yes 的表达式,但前提是它前面没有字符串 no

例如,这与匹配:Hello world, major yes here!
但这不会匹配:Hell no yes

第二个字符串不匹配,因为 yes 字符串前面是 no 字符串。显然这需要否定的后视,它不是以 JavaScript 正则表达式的形式实现的,我试过这样的东西:/((?!no ))yes/
/^(?!.*no) 是$/

但他们似乎并没有达到预期的效果:/

最佳答案

你可以试试下面的正则表达式。

^(?=(?:(?!\bno\b).)*yes).*

DEMO

解释:

^                        the beginning of the string
(?= look ahead to see if there is:
(?: group, but do not capture (0 or more
times):
(?! look ahead to see if there is not:
\b the boundary between a word char
(\w) and something that is not a
word char
no 'no'
\b the boundary between a word char
(\w) and something that is not a
word char
) end of look-ahead
. any character except \n
)* end of grouping
yes 'yes'
) end of look-ahead
.* any character except \n (0 or more times)

关于javascript - 在 JavaScript 中匹配一个单词而不匹配另一个单词的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26453329/

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