使用正则表达式反转匹配
使用 PCRE,如何构造一个仅在找不到字符串时才匹配的表达式。
如果我使用 grep (我没有),我会想要 -v 选项。
一个更具体的例子:我希望我的正则表达式匹配当且仅当字符串 foo
是 not 在字符串中。 所以它会匹配 bar
但不会匹配 foobar
。
With PCRE, how can you construct an expression that will only match if a string is not found.
If I were using grep (which I'm not) I would want the -v option.
A more concrete example: I want my regexp to match iff string foo
is not in the string. So it would match bar
would but not foobar
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好的,我已经根据您提出的解决方案改进了我的正则表达式(它错误地匹配以“test”开头的字符串)。
此正则表达式将仅匹配不包含 foo 的字符串。 第一个前瞻将拒绝以“foo”开头的字符串,第二个前瞻将确保在字符串的其他位置找不到 foo。
Okay, I have refined my regular expression based on the solution you came up with (which erroneously matches strings that start with 'test').
This regular expression will match only strings that do not contain foo. The first lookahead will deny strings beginning with 'foo', and the second will make sure that foo isn't found elsewhere in the string.
根据丹尼尔的回答,我认为我已经得到了一些有用的东西:
关键是你需要对字符串中的每个字符做出否定断言
Based on Daniel's answer, I think I've got something that works:
The key is that you need to make the negative assertion on every character in the string
这确实几乎是重复的。 我猜你正在寻找的正则表达式是
(?!foo).*
It's indeed almost a duplicate. I guess the regex you're looking for is
(?!foo).*
构建匹配的表达式,并使用 !match()...(逻辑否定)
无论如何,这可能就是 grep 的作用......
Build an expression that matches, and use !match()... (logical negation)
That's probably how grep does anyway...
您还可以通过使用
re.split
来执行此操作(在 python 中),并根据正则表达式进行拆分,从而返回与正则表达式不匹配的所有部分,根据与正则表达式不匹配的内容进行分割You can also do this (in python) by using
re.split
, and splitting based on your regular expression, thus returning all the parts that don't match the regex, splitting based on what doesn't match a regularexpression