views:

56

answers:

3

Possible Duplicate:
What regular expression can never match?

I'm looking for a regular expression that will not match any string. Example:

suppose I have the following Java code

public boolean checkString(String lineInput, String regex)
{
    final Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    final Matcher m = p.matcher(lineInput);
    return m.matches();
}

In some conditions I want that checkString will return false for all all lineInput.Cause I control only regex (and not lineInput) is there a value that will NOT match any string ?

-- Yonatan

+2  A: 

\b\B will not match any string since it's a contradiction.

\b is a zero-width anchor that matches the word boundary. \B is also zero-length, and sits wherever \b doesn't. Therefore it's simply impossible to witness \b and \B together.

If the regex flavor supports lookarounds, you can also use negative lookahead (?!). This assertion will always fail since it's always possible to match an empty string.

As Java String literals, the patterns above are "\\b\\B" and "(?!)" respectively.

References

polygenelubricants
A: 

You could also try these old, esoteric characters that aren't really used anymore (although technically could be matched):

\f  The form-feed character ('\u000C')
\a  The alert (bell) character ('\u0007')
\e  The escape character ('\u001B')
adamd
Doesn't convey intent, and not 100% guaranteed to fail.
polygenelubricants
A: 

I think the sensible way to do this would be like so:

private boolean noMatch = false;

public void setNoMatch(boolean nm) { noMatch = nm; }

public boolean checkString(String lineInput, String regex)
{
    if (noMatch) return false;
    final Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    final Matcher m = p.matcher(lineInput);
    return m.matches();
}

Creating a non-matching regex sounds like a horrible kludge and an abuse of regex. If you know there won't be a match, then say so in your code! Your code will thank you for it by being more understandable and running faster.

Carl Smotricz