如何使用正则表达式否定字符串
任何人都可以告诉我如何使用正则表达式来否定字符串吗? 我想找到所有以 public class
开头的行,然后是 除第一个、第二个之外的任何内容
,最后是其他任何内容。
例如,在结果中我希望看到 public class base
但不是 public class myfirst:base
请问有人可以帮助我吗?
can any body tell me how to use regex for negation of string?
I wanna find all line that start with public class
and then any thing except first,second
and finally any thing else.
for example in the result i expect to see public class base
but not public class myfirst:base
can any body help me please??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用负前瞻:
Use a negative lookahead:
如果 Peter 是正确的,并且您正在使用 Visual Studio 的
Find
功能,则这应该有效::b
匹配空格或制表符~(...)
是 VS 进行负向预测的方式:i
匹配 C/C++ 标识符其余部分是标准正则表达式语法:
^
表示行首$
表示行尾.
代表任何字符*
表示零个或多个+
表示一个或多个|
用于交替If Peter is correct and you're using Visual Studio's
Find
feature, this should work::b
matches a space or tab~(...)
is how VS does a negative lookahead:i
matches a C/C++ identifierThe rest is standard regex syntax:
^
for beginning of line$
for end of line.
for any character*
for zero or more+
for one or more|
for alternation其他两个答案都很接近,但可能由于不同的原因而失败。
请注意负前瞻周围有一个(非捕获)组,以确保它不仅仅适用于第一个位置。
而且该组限制较少 - 由于
.
不包括换行符,因此它使用换行符而不是\S
,并且$
不是必需的 - 这将排除指定的单词并匹配其他单词。表达式中没有斜杠,因为并非所有内容都需要斜杠,并且可能会让只遇到过基于字符串的正则表达式使用的人感到困惑。
如果仍然失败,请发布错误匹配或遗漏的确切内容,以及您使用的语言/IDE。
更新:
原来您使用的是 Visual Studio,它有自己的 特殊的正则表达式实现。所以,你会想尝试这个:
我无法测试它 - 如果它不起作用,请尝试删除
$
,但否则你将不得不找到一个 VS 用户。或者更好的是,VS 工程师负责这个愚蠢的非标准正则表达式。Both the other two answers come close, but probably fail for different reasons.
Note how there is a (non-capturing) group around the negative lookahead, to ensure it applies to more than just the first position.
And that group is less restrictive - since
.
excludes newline, it's using that instead of\S
, and the$
is not necessary - this will exclude the specified words and match others.No slashes wrapping the expression since those aren't required in everything and may confuse people that have only encountered string-based regex use.
If this still fails, post the exact content that is wrongly matched or missed, and what language/ide you are using.
Update:
Turns out you're using Visual Studio, which has it's own special regex implementation, for some unfathomable reason. So, you'll be wanting to try this instead:
I have no way of testing that - if it doesn't work, try dropping the
$
, but otherwise you'll have to find a VS user. Or better still, the VS engineer(s) responsible for this stupid non-standard regex.这是应该对您有用的
第二个外观,可以将头部更改为 $(行尾)或适合您的特定用例的另一个锚点,例如“{”
编辑:尝试将最后一部分更改为:
Here is something that should work for you
The second look a head could be changed to a $(end of line) or another anchor that works for your particular use case, like maybe a '{'
Edit: Try changing the last part to: