Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace words using regex [duplicate]

Tags:

java

regex

Possible Duplicate:
regex replace all ignore case

I need to replace all occurrences of Sony Ericsson with a tilda in between them. This is what I have tried

String outText="";
    String inText="Sony Ericsson is a leading company in mobile. The company sony ericsson was found in oct 2001";
    String word = "sony ericsson";
    outText = inText.replaceAll(word, word.replaceAll(" ", "~"));
    System.out.println(outText);

The output of this is

Sony Ericsson is a leading company in mobile. The company sony~ericsson was found in oct 2001

But what I want is

Sony~Ericsson is a leading company in mobile. The company sony~ericsson was found in oct 2001

It should ignore cases & give the desired output.

like image 563
lambda123 Avatar asked Aug 12 '26 09:08

lambda123


2 Answers

Change it to

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

to make the search / replace case insensitive.

String outText="";
String inText="Sony Ericsson is a leading company in mobile. " +
              "The company sony ericsson was found in oct 2001";
String word = "sony ericsson";
outText = inText.replaceAll("(?i)" + word, word.replaceAll(" ", "~"));
System.out.println(outText);

Output:

sony~ericsson is a leading company in mobile.
The company sony~ericsson was found in oct 2001

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 142
aioobe Avatar answered Aug 15 '26 00:08

aioobe


str.replaceAll(regex, repl) is equal to Pattern.compile(regex).matcher(str).replaceAll(repl). Thus, you can make your matcher case-insensitive with a flag:

Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(str).replaceAll(repl)

Using backreferences to preserve case:

Pattern.compile("(sony) (ericsson)", Pattern.CASE_INSENSITIVE)
       .matcher(str)
       .replaceAll("$1~$2")

Gives:

Sony~Ericsson is a leading company in mobile. The company sony~ericsson was found in oct 2001

like image 30
jensgram Avatar answered Aug 15 '26 01:08

jensgram