使用正则表达式反转匹配

发布于 2024-07-22 10:04:10 字数 208 浏览 3 评论 0原文

使用 PCRE,如何构造一个仅在找不到字符串时才匹配的表达式。

如果我使用 grep (我没有),我会想要 -v 选项。

一个更具体的例子:我希望我的正则表达式匹配当且仅当字符串 foonot 在字符串中。 所以它会匹配 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

拒绝两难 2024-07-29 10:04:10

好的,我已经根据您提出的解决方案改进了我的正则表达式(它错误地匹配以“test”开头的字符串)。

^((?!foo).)*$

此正则表达式将仅匹配不包含 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').

^((?!foo).)*$

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.

写给空气的情书 2024-07-29 10:04:10

根据丹尼尔的回答,我认为我已经得到了一些有用的东西:

^(.(?!test))*$

关键是你需要对字符串中的每个字符做出否定断言

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

假装爱人 2024-07-29 10:04:10

这确实几乎是重复的。 我猜你正在寻找的正则表达式是

(?!foo).*

It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*

提赋 2024-07-29 10:04:10

构建匹配的表达式,并使用 !match()...(逻辑否定)
无论如何,这可能就是 grep 的作用......

Build an expression that matches, and use !match()... (logical negation)
That's probably how grep does anyway...

夏雨凉 2024-07-29 10:04:10

您还可以通过使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文