A Regex that will never be matched by anything
Leverage negative lookahead
:
>>> import re
>>> x=r'(?!x)x'
>>> r=re.compile(x)
>>> r.match('')
>>> r.match('x')
>>> r.match('y')
this RE is a contradiction in terms and therefore will never match anything.
NOTE:
In Python, re.match() implicitly adds a beginning-of-string anchor (\A
) to the start of the regular expression. This anchor is important for performance: without it, the entire string will be scanned. Those not using Python will want to add the anchor explicitly:
\A(?!x)x
This is actually quite simple, although it depends on the implementation / flags*:
$a
Will match a character a
after the end of the string. Good luck.
WARNING:
This expression is expensive -- it will scan the entire line, find the end-of-line anchor, and only then not find the a
and return a negative match. (See comment below for more detail.)
* Originally I did not give much thought on multiline-mode regexp, where $
also matches the end of a line. In fact, it would match the empty string right before the newline, so an ordinary character like a
can never appear after $
.