-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.

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

2

You could do

str = 
   str.replace("woman", "REPLACEMENT1")
   .replace("man", "REPLACEMENT2")
   .replace("girls", "REPLACEMENT3");

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.