我知道可以匹配一个单词,然后用其他工具逆转比赛(例如 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"]

其他回答

如果你只是用它来捕捉,你可以使用捕捉 -v 以获得所有不包含捕捉的线条。

ETA Oh,重新阅读这个问题,抓 -v 可能是你指的是“工具选项”。

我必须同意其他答案,但是:如果这只是假设问题,那么一个假设不是正确的选择。

我想添加另一个例子,如果你试图匹配一个包含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

也许你会在谷歌上找到这一点,同时试图写一个能够匹配一行(与整个行相反)的分区,这些分区不包含一个字符。

根据字符串: <span class="good">bar</span><span class="bad">foo</span><span class="ugly">baz</span>

我想匹配 <span> 标签,这些标签不包含“坏”字符。

/<span(?:(?!坏)*?>将匹配 <span class=\"good\">和 <span class=\"ugly\">。

请注意,有两组(层)的偏见:

最内在的是对负面观点(这不是捕捉群体) 最外在是由Ruby作为捕捉群体解释的,但我们不希望它成为捕捉群体,所以我补充说:它是开始,它不再被解释为捕捉群体。

在Ruby中展示:

s = '<span class="good">bar</span><span class="bad">foo</span><span class="ugly">baz</span>'
s.scan(/<span(?:(?!bad).)*?>/)
# => ["<span class=\"good\">", "<span class=\"ugly\">"]