Is Java RegEx case-insensitive?

Crystal picture Crystal · Aug 8, 2010 · Viewed 148.8k times · Source

In Java, when doing a replaceAll to look for a regex pattern like:

replaceAll("\\?i\\b(\\w+)\\b(\\s+\\1)+\\b", "$1"); 

(to remove duplicate consecutive case-insensitive words, e.g. Test test), I'm not sure where I put the ?i. I read that it is supposed to be at the beginning, but if I take it out then i catch duplicate consecutive words (e.g. test test), but not case-insensitive words (e.g. Test test). So I thought I could add the ?i in the beginning but that does not seem to get the job done. Any thoughts? Thanks!

Answer

Christian Vielma picture Christian Vielma · Oct 2, 2014

You can also match case insensitive regexs and make it more readable by using the Pattern.CASE_INSENSITIVE constant like:

Pattern mypattern = Pattern.compile(MYREGEX, Pattern.CASE_INSENSITIVE);
Matcher mymatcher= mypattern.matcher(mystring);