Is it possible to write a regex that returns the converse of a desired result? Regexes are usually inclusive - finding matches. I want to be able to transform a regex into
You can also do this (in python) by using re.split
, and splitting based on your regular expression, thus returning all the parts that don't match the regex, how to find the converse of a regex
Java Regexps have an interesting way of doing this (can test here) where you can create a greedy optional match for the string you want, and then match data after it. If the greedy match fails, it's optional so it doesn't matter, if it succeeds, it needs some extra data to match the second expression and so fails.
It looks counter-intuitive, but works.
Eg (foo)?+.+
matches bar
, foox
and xfoo
but won't match foo
(or an empty string).
It might be possible in other dialects, but couldn't get it to work myself (they seem more willing to backtrack if the second match fails?)
You can invert the character set by writing a ^
at the start ([^…]
). So the opposite expression of [ab]
(match either a
or b
) is [^ab]
(match neither a
nor b
).
But the more complex your expression gets, the more complex is the complementary expression too. An example:
You want to match the literal foo
. An expression, that does match anything else but a string that contains foo
would have to match either
foo
(^.{0,2}$
), orfoo
(^([^f]..|f[^o].|fo[^o])$
), orfoo
.All together this may work:
^[^fo]*(f+($|[^o]|o($|[^fo]*)))*$
But note: This does only apply to foo
.
In perl you can anti-match with $string !~ /regex/;
.
Couldn't you just check to see if there are no matches? I don't know what language you are using, but how about this pseudocode?
if (!'Some String'.match(someRegularExpression))
// do something...
If you can only change the regex, then the one you got from your link should work:
/^((?!REGULAR_EXPRESSION_HERE).)*$/
With grep, you can use --invert-match
or -v
.