Friday, 17 September 2010

Escaping a regex expression

I was working on a project where I needed to dynamically generate a regular expression based on some user input but the string to search for needed to be escaped. Below is the quick and dirty way to do it:
/**
 * Utility function to replace regular expressions.
 *
 * @param input
 * @return
 */
private static String escapeRegex(String input)
{
    String special[] = { "\\", "[", "]", "^", "$", ".", "|", "?", "*", "+", "(", ")" };
    String val = input;
    for (String replace : special)
    {
        val = val.replace(replace, "\\" + replace);
    }

    return val;
}

No comments:

Post a Comment