Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex replace all ignore case

Tags:

java

regex

How do I ignore case in the below example?

outText = inText.replaceAll(word, word.replaceAll(" ", "~"));

Example:

Input:

inText = "Retail banking Wikipedia, the free encyclopedia Retail banking "
       + "From Wikipedia. retail banking industry."

word   = "retail banking"

Output

outText = "Retail~banking Wikipedia, the free encyclopedia Retail~banking " +
          "From Wikipedia. retail~banking industry."
like image 571
dazzle Avatar asked Apr 06 '11 14:04

dazzle


3 Answers

To do case-insensitive search and replace, you can change

outText = inText.replaceAll(word, word.replaceAll(" ", "~"));

into

outText = inText.replaceAll("(?i)" + word, word.replaceAll(" ", "~"));

Avoid ruining the original capitalization:

In the above approach however, you're ruining the capitalization of the replaced word. Here is a better suggestion:

String inText="Sony Ericsson is a leading company in mobile. " +
              "The company sony ericsson was found in oct 2001";
String word = "sony ericsson";

Pattern p = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(inText);

StringBuffer sb = new StringBuffer();

while (m.find()) {
  String replacement = m.group().replace(' ', '~');
  m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
m.appendTail(sb);

String outText = sb.toString();

System.out.println(outText);

Output:

Sony~Ericsson is a leading company in mobile.
The company sony~ericsson was found in oct 2001
like image 176
aioobe Avatar answered Nov 15 '22 19:11

aioobe


You could convert it all to lowercase before doing the search, or look at a regex modifier Pattern.CASE_INSENSITIVE

like image 32
AlanFoster Avatar answered Nov 15 '22 18:11

AlanFoster


Here is my way of doing it:

        private String replaceAllIgnoreCase(final String text, final String search, final String replacement){
        if(search.equals(replacement)) return text;
        final StringBuffer buffer = new StringBuffer(text);
        final String lowerSearch = search.toLowerCase(Locale.CANADA);
        int i = 0;
        int prev = 0;
        while((i = buffer.toString().toLowerCase(Locale.CANADA).indexOf(lowerSearch, prev)) > -1){
            buffer.replace(i, i+search.length(), replacement);
            prev = i+replacement.length();
        }
        return buffer.toString();
    }

Seems to work flawlessly up to my extent. The good thing about doing it my way is that there is no regex in my solution, meaning if you wanted to replace a bracket or a plus sign (or any other meta character for that matter) it will actually replace the text for what it actually is, rather than what it means in regex. Hope this has helped.

like image 27
Josh M Avatar answered Nov 15 '22 19:11

Josh M