开发者

how to use regex negation string

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??


Use a negative lookahead:

public\s+class\s+(?!first|second).+


If Peter is correct and you're using Visual Studio's Find feature, this should work:

^:b*public:b+class:b+~(first|second):i.*$

:b matches a space or tab
~(...) is how VS does a negative lookahead
:i matches a C/C++ identifier

The 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


Both the other two answers come close, but probably fail for different reasons.

public\s+class\s+(?:(?!first|second).)+

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:

public:b+class:b+~(first|second)+$

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

/public\sclass\s(?:[^fs\s]+|(?!first|second)\S)+(?=\s|$)/

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:

(?=\s|$)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜