Java Regular expression does not match using Apache RE

I have this regular expression string:

^[a-zA-Z0-9tsnr!$()*,-./:;[email protected]`][{}_~|]+$

This RE should return true for the following:

!$()*,-./:;[email protected]`][{}_~|

I’m using RE of Apache and get false when running match function.
I think my regular expression is missing something, maybe handling with special characters.
The question is, what is wrong with my expression?
here is my RE matching function:

public static String runRegularExpression(String string, String regularExpression, int parenthesis)
{
    String result = null;

    try
    {
        RE reCmd = new RE(regularExpression);

        if (reCmd.match(string))
        {
            result = reCmd.getParen(parenthesis);
        }
    }
    catch (Exception re)
    {
    }

    return result;
}

Answer

  1. You regex must not have unescaped hyphen in the middle of character class.
  2. If you already have s then there is no need to match n and t since s matches all white-spaces that includes space, tab and newlines.
  3. [a-zA-Z0-9_] can be shortened to w
  4. Backslashes need to be double escaped.

Try this regex:

^[\w\s\r!$()*,./:;[email protected]`{}\[\]~|-]+$

Leave a Reply

Your email address will not be published. Required fields are marked *