Pattern syntax Regular expression exception built with entered text

I am parsing .txt, line by line, given the target token. I am using the regex processor engine.

I am matching each line with:

"(^|.*[\\s])"+token+"([\\s].*|$)"

      

where token is a string. When:

token="6-7(3-7" 

      

the following exception is thrown:

Exception in thread "main" java.util.regex.PatternSyntaxException: 
Unclosed    group near index 27
(^|.*[\s])6-7(3-7([\s].*|$)

      

How can I solve this?

+3


source to share


2 answers


You have special characters in your token.

Take a look Pattern.quote()

:

public static String quote (String s)

Returns the String pattern for the specified string.

This method creates a string that can be used to create a pattern that matches the string s as if it were a literal pattern.

Metacharacters or escape sequences in the input sequence will have no special meaning.



This should do the trick for you:

String pattern = "(^|.*[\\s])" + Pattern.quote(token) + "([\\s].*|$)";

      

No need to do string magic yourself! :-)

+8


source


You should avoid special characters in any line of plain text used to create regex patterns. Replace "("

with "\("

and in a similar manner for bare backslashes (before any other steps), periods, and all other special characters, at least whatever you expect to see in the input. (If this is arbitrary input from users, assume each character is included.)



+1


source







All Articles