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

[379 byte] By [manuel.leiriaa] at [2007-11-27 1:55:16]
# 1
Check out \Q and \E in the Javadoc for Pattern.
sabre150a at 2007-7-12 1:28:01 > top of Java-index,Java Essentials,Java Programming...
# 2
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.)
paulcwa at 2007-7-12 1:28:01 > top of Java-index,Java Essentials,Java Programming...
# 3

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);

uncle_alicea at 2007-7-12 1:28:01 > top of Java-index,Java Essentials,Java Programming...
# 4

> 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

manuel.leiriaa at 2007-7-12 1:28:01 > top of Java-index,Java Essentials,Java Programming...