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