-1

How can I replace different match with different replacement regex if I have two match option separated by |, for each of the match I want to reference the string or substring that matches. if I have

Pattern p = Pattern.compile("man|woman|girls");
Matcher m = p.matcher("some string");

If the match is "man" I want to use a different replacement from when the match is "woman" or "girls".

I have looked through Most efficient way to use replace multiple words in a string but dont understand how to reference the match itself.

Community
  • 1
  • 1
Ibukun Muyide
  • 1,294
  • 1
  • 15
  • 23

2 Answers2

2

You could do

str = 
   str.replace("woman", "REPLACEMENT1")
   .replace("man", "REPLACEMENT2")
   .replace("girls", "REPLACEMENT3");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • okay thanks, but was hoping to use something of this nature while (m.find()) { m.appendReplacement(); }. found out its its does not use much of the cpu resources – Ibukun Muyide Apr 21 '15 at 10:19
2

Consider improving your pattern a little to add word-boundries to prevent it from patching only some part of words like man can be match for mandatory.

(BTW: Also in case you would want to replace words which have same start like man and manual you should place manual before man in regex, or man will consume <man>ual part which will prevent ual from being match. So correct order would be manual|man)

So your regex can look more like

Pattern p = Pattern.compile("\\b(man|woman|girls)\\b");
Matcher m = p.matcher("some text about woman and few girls");

Next thing you can do is simply store pairs originalValue -> replacement inside some collection which will let you easily get replacement for value. Simplest way would be using Map

Map<String, String> replacementMap = new HashMap<>();
replacementMap.put("man", "foo");
replacementMap.put("woman", "bar");
replacementMap.put("girls", "baz");

Now your code can look like this:

StringBuffer sb = new StringBuffer();
while(m.find()){
    String wordToReplace = m.group();
    //replace found word with with its replacement in map
    m.appendReplacement(sb, replacementMap.get(wordToReplace));
}
m.appendTail(sb);

String replaced = sb.toString();
Pshemo
  • 122,468
  • 25
  • 185
  • 269