Reputation: 73
I'm working with Perl to search and match for strings on each line that match a criteria and would like to omit the lines that contain a specific string. What I mean is: Say I'm matching the string Mouse, but I'd like to omit if the line matches X123Y. Either strings can be found anywhere on the line.
Stackoverflow Mouse forum. <--Match
Stackoverflow -Mouse- forum. <--Match
Stackoverflow X123Y forum Mouse. <--Should not Match
Stackoverflow XYZ forum Mouse. <--Should not Match
I hoped this would solve it since I'm using negative lookahead but doesn't seem to do the trick.
(?i)(\WMouse\W|(?!(X123Y|XYZ)).*$)
I'm doing something fundamentally wrong I suppose, but cannot see it now.
Any help?
Upvotes: 5
Views: 129
Reputation: 31025
You can use the discard technique to keep with the content you want and discard the patterns you don't.
For example, using this regex:
.*X123Y.*|.*XYZ.*|(.*Mouse.*)
You will grab the content for the rightest pattern and discard the others..
The idea is to use:
discard patt 1 | discard patt 2 | discard patt n | (grab this pattern)
Upvotes: 1
Reputation: 785286
This regex should work for you:
^(?=.*?Mouse)(?:(?!(?:X123|XYZ)).)*$
Upvotes: 4