PatternSyntaxException
Hi,
I have this
Pattern pattern = Pattern.compile(wordToSearch.toUpperCase());
Matcher matcher = pattern.matcher(singleWord.toUpperCase());
but if the String wordToSearch contains a ( I receive an java.util.regex.PatternSyntaxException: Unclosed group near index...
How to escape this characteres?
thanks in advance,
Manuel Leiria
I'd recommend against passing a pattern through toUpperCase() (or, for that matter, toLowerCase()) before compiling it, because some regex constructs can change meaning significantly when the case is changed. (For example, \s matches whitespace, but \S matches non-whitespace.)
The OP is obviously just trying to match the search term literally, not as a regex, but converting it or the search target to uppercase is still wrong. @OP, if you're working with JDK 1.5 or later, do this: Pattern pattern = Pattern.compile(Pattern.quote(wordToSearch),
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(singleWord);
If you're still on 1.4, you can quote it manually, as Sabre suggested:Pattern pattern = Pattern.compile("\\Q" + wordToSearch + "\\E",
Pattern.CASE_INSENSITIVE);
> The OP is obviously just trying to match the search
> term literally, not as a regex, but converting it or
> the search target to uppercase is still wrong. @OP,
> if you're working with JDK 1.5 or later, do this:
> > Pattern pattern =
> Pattern.compile(Pattern.quote(wordToSearch),
>
> attern.CASE_INSENSITIVE);
> Matcher matcher = pattern.matcher(singleWord);
> If you're still on 1.4, you can quote it manually, as
> Sabre suggested:> Pattern pattern = Pattern.compile("\\Q" +
> wordToSearch + "\\E",
>
> attern.CASE_INSENSITIVE);
That's it. thanks you guys!
Manuel Leiria