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

入口:

hoho
hihi
haha
hede

代码:

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

所需的产量:

hoho
hihi
haha

当前回答

如果你想匹配一个字符,否认类似于否认字符类的单词:

例如,一条线:

<?
$str="aaa        bbb4      aaa     bbb7";
?>

不要使用:

<?
preg_match('/aaa[^bbb]+?bbb7/s', $str, $matches);
?>

使用:

<?
preg_match('/aaa(?:(?!bbb).)+?bbb7/s', $str, $matches);
?>

警告“(?!bbb.)”不是 lookbehind 或 lookahead,它是 lookcurrent,例如:

"(?=abc)abcde", "(?!abc)abcde"

其他回答

这就是我这样做的方式:

^[^h]*(h(?!ede)[^h]*)*$

比其他答案更准确、更有效,它实施了弗里德尔的“无滚动”效率技术,需要更少的后续追踪。

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

TXR 语言支持 regex 拒绝。

$ txr -c '@(repeat)
@{nothede /~hede/}
@(do (put-line nothede))
@(end)'  Input

一个更复杂的例子:匹配所有从 a 开始和 z 结束的线条,但不包含底层的线条:

$ txr -c '@(repeat)
@{nothede /a.*z&~.*hede.*/}
@(do (put-line nothede))
@(end)' -
az         <- echoed
az
abcz       <- echoed
abcz
abhederz   <- not echoed; contains hede
ahedez     <- not echoed; contains hede
ace        <- not echoed; does not end in z
ahedz      <- echoed
ahedz

雷格克斯的拒绝本身并不特别有用,但当你也有交叉时,事情变得有趣,因为你有一个完整的布莱恩组操作:你可以表达“与此相匹配的组,除了与此相匹配的东西”。

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

使用 ConyEdit,您可以使用命令行 cc.gl!/hede/ 获取不包含 regex 匹配的行,或者使用命令行 cc.dl /hede/ 删除包含 regex 匹配的行。