我知道可以匹配一个单词,然后用其他工具逆转比赛(例如 grep -v)。但是,可以匹配不包含一个特定的单词,例如 hede,使用常规表达式的线条吗?
入口:
hoho
hihi
haha
hede
代码:
grep "<Regex for 'doesn't contain hede'>" input
所需的产量:
hoho
hihi
haha
我知道可以匹配一个单词,然后用其他工具逆转比赛(例如 grep -v)。但是,可以匹配不包含一个特定的单词,例如 hede,使用常规表达式的线条吗?
入口:
hoho
hihi
haha
hede
代码:
grep "<Regex for 'doesn't contain hede'>" input
所需的产量:
hoho
hihi
haha
当前回答
OP 没有指定或标记帖子,以显示背景(编程语言、编辑器、工具)中将使用 Regex。
对于我来说,有时我需要在使用 Textpad 编辑文件时做到这一点。
Textpad 支持一些 Regex,但不支持 lookahead 或 lookbehind,所以需要几步。
Search string:^(.)
Replace string:<@#-unique-#@>\1
Replace-all
Search string:<@#-unique-#@>.*hede.*\n
Replace string:<nothing>
Replace-all
此分類上一篇
此分類上一篇
Search string:<@#-unique-#@>
Replace string:<nothing>
Replace-all
现在你有原始文本,所有包含字符串的线条已被删除。
此分類上一篇
Search string:^(.)
Replace string:<@#-unique-#@>\1
Replace-all
对于包含字符串标签的所有行,请删除独特的“标签”:
Search string:<@#-unique-#@>(.*hede)
Replace string:\1
Replace-all
此分類上一篇
此时此刻,所有以独特的“标签”开始的线条,不包含线条标签,我现在只能用这些线条来做我的某事。
当我完成时,我将从所有行中删除独特的“标签”(替换行是空的):
Search string:<@#-unique-#@>
Replace string:<nothing>
Replace-all
其他回答
如果您希望 regex 测试只会失败,如果整个序列相匹配,则下列内容将工作:
^(?!hede$).*
例如 - 如果你想允许除了“foo”以外的所有值(即“foofoo”,“barfoo”和“foobar”将通过,但“foo”将失败),请使用: ^(?!foo$)。
当然,如果你正在检查准确的平等,在这种情况下,一个更好的总体解决方案是检查序列平等,也就是说。
myStr !== 'foo'
您甚至可以将拒绝置于测试之外,如果您需要任何 regex 功能(这里,案例不敏感性和范围匹配):
!/^[a-f]oo$/i.test(myStr)
但是,这个答案的顶部的 regex 解决方案在需要积极的 regex 测试的情况下可能有用(可能是通过 API)。
这就是我这样做的方式:
^[^h]*(h(?!ede)[^h]*)*$
比其他答案更准确、更有效,它实施了弗里德尔的“无滚动”效率技术,需要更少的后续追踪。
不是雷格斯,但我发现使用带管的序列粘贴是合乎逻辑和有用的,以消除噪音。
例如,搜索一个 Apache 配置文件,没有所有评论 -
grep -v '\#' /opt/lampp/etc/httpd.conf # this gives all the non-comment lines
和
grep -v '\#' /opt/lampp/etc/httpd.conf | grep -i dir
序列格雷普的逻辑是(不是一个评论)和(比赛是)
更简单的解决方案是使用非运营商!
如果您的声明需要匹配“内容”而不匹配“排除”。
var contains = /abc/;
var excludes =/hede/;
if(string.match(contains) && !(string.match(excludes))){ //proceed...
我相信RegEx的设计师预测了非运营商的使用。
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
雷格克斯的拒绝本身并不特别有用,但当你也有交叉时,事情变得有趣,因为你有一个完整的布莱恩组操作:你可以表达“与此相匹配的组,除了与此相匹配的东西”。