Reputation: 21
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??
Upvotes: 2
Views: 4501
Reputation: 75222
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
Upvotes: 3
Reputation: 112150
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.
Upvotes: 1
Reputation: 712
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|$)
Upvotes: 0