我知道可以匹配一个单词,然后用其他工具逆转比赛(例如 grep -v)。但是,可以匹配不包含一个特定的单词,例如 hede,使用常规表达式的线条吗?

入口:

hoho
hihi
haha
hede

代码:

grep "<Regex for 'doesn't contain hede'>" input

所需的产量:

hoho
hihi
haha

当前回答

自推出Ruby-2.4.1以来,我们可以在Ruby的常规表达中使用新缺席运营商。

官方DOC

(?~abc) matches: "", "ab", "aab", "cccc", etc.
It doesn't match: "abc", "aabc", "ccccabc", etc.

因此,在你的情况下 ^(?~hede)$ 为你做工作

2.4.1 :016 > ["hoho", "hihi", "haha", "hede"].select{|s| /^(?~hede)$/.match(s)}
 => ["hoho", "hihi", "haha"]

其他回答

^((?!hede).) *$ 是一个优雅的解决方案,除非它消耗字符,你将无法将其与其他标准相结合。 例如,说你想检查“hede”的不存在和“haha”的存在。

^(?!.*\bhede\b)(?=.*\bhaha\b) 

用此,你避免在每个位置测试一个 lookahead:

/^(?:[^h]+|h++(?!ede))*+$/

相当于(为.net ):

^(?>(?:[^h]+|h+(?!ede))*)$

老答案:

/^(?>[^h]+|h+(?!ede))*$/

我想添加另一个例子,如果你试图匹配一个包含X线的整个线,但也不包含Y线。

这个 regex 模式会工作(在 JavaScript 中也工作)

^(?=.*?tasty-treats)((?!chocolate).)*$

(全球,多线旗在例子中)

互动示例: https://regexr.com/53gv4

比赛

(这些 URL 包含“蛋糕治疗”并且不包含“巧克力”)

example.com/tasty-treats/strawberry-ice-cream example.com/甜点/tasty-treats/banana-pudding example.com/tasty-treats-overview

没有匹配

example.com/tasty-treats/chocolate-cake example.com/home-cooking/over-roasted-chicken example.com/tasty-treats/banana-chocolate-fudge example.com/desserts/chocolate/tasty-treats example.com/chocolate/tasty-treats/desserts

此前提到的(?(?!)*是很棒的,因为它可以被 anchored。

^(?:(?!hede).)*$               # A line without hede

foo(?:(?!hede).)*bar           # foo followed by bar, without hede between them

但在这种情况下,以下几点就足够了:

^(?!.*hede)                    # A line without hede

此简化已准备好添加“和”条款:

^(?!.*hede)(?=.*foo)(?=.*bar)   # A line with foo and bar, but without hede
^(?!.*hede)(?=.*foo).*bar       # Same

答案非常好,只是一个学术点:

计算机科学的理论意义上的常规表达是不可能这样做的,对他们来说,它应该看起来像这样:

^([^h].*$)|(h([^e].*$|$))|(he([^h].*$|$))|(heh([^e].*$|$))|(hehe.+$) 

这只是一场完整的比赛,做下一场比赛会更可怕。