Which regular expression can I use to find all strings bar
are not preceded by string foo
? Having whitespace between the two is also illegal.
So the regex should match the following strings
foo is bar
hello bar
But not these
foobar
foo bar
I've tried using the following
(?!<foo)bar
and it gets the work done for eliminating foobar
, but I need to take care of the whitespace, and of course
(?!<foo)\s*bar
matches all the strings.
Thanks!
Given a few test cases
you could of course do by feeding the results of one pattern to another:
We can also do it with one:
But don't take my word for it.
This will match the whitespace
Better to use other facilities of the programming language than to look too hard for a regex pattern.
You are looking for strings for which
$s =~ /bar/ and not $s =~ /foo\s*bar/
is true.The rest of the script below is just for testing.
Output:
Taking the information from earlier answers, wrapping as a perl one-liner, and making the regular expressions case-insensitive.
Windows:
Linux:
With xx.txt containing:
The result of executing the one-liner at a command prompt:
php:
perl: