匹配不包含特定文本的行与正则表达式

时间:2022-09-23 01:06:09

I want to do the following with regular expressions but not sure how to do it. I want it to match one two when one two is the beginning of the line unless the string contains three anywhere after one two.

我想用正则表达式执行以下操作,但不确定如何执行此操作。我希望它匹配一个二,当一个两个是行的开头,除非字符串包含三个在两个之后的任何地方。

2 个解决方案

#1


14  

You need a negative lookahead assertion - something like this:

你需要一个负面的先行断言 - 像这样:

/^one two(?!.*three)/m

Here's a tutorial on lookahead/lookbehind assertions

这是一个关于前瞻/后瞻断言的教程

Note: I've added the 'm' modifier so that ^ matches the start of a line rather than the start of the whole string.

注意:我添加了'm'修饰符,以便^匹配行的开头而不是整个字符串的开头。

#2


4  

^one two(?!.*three)

#1


14  

You need a negative lookahead assertion - something like this:

你需要一个负面的先行断言 - 像这样:

/^one two(?!.*three)/m

Here's a tutorial on lookahead/lookbehind assertions

这是一个关于前瞻/后瞻断言的教程

Note: I've added the 'm' modifier so that ^ matches the start of a line rather than the start of the whole string.

注意:我添加了'm'修饰符,以便^匹配行的开头而不是整个字符串的开头。

#2


4  

^one two(?!.*three)