I'm looking for the best approach for string find and replace in Java.
This is a sentence: "My name is Milan, people know me as Milan Vasic".
I want to replace the string Milan with Milan Vasic, but on place where I have already Milan Vasic, that shouldn't be a case.
after search/replace result should be: "My name is Milan Vasic, people know me as Milan Vasic".
I was try to use indexOf() and also Pattern/Matcher combination, but neither of my results not looks elegant, does someone have elegant solution?
cheers!
解决方案
Well, you can use a regular expression to find the cases where "Milan" isn't followed by "Vasic":
Milan(?! Vasic)
and replace that by the full name:
String.replaceAll("Milan(?! Vasic)", "Milan Vasic")
The (?!...) part is a negative lookahead which ensures that whatever matches isn't followed by the part in parentheses. It doesn't consume any characters in the match itself.
Alternatively, you can simply insert (well, technically replacing a zero-width match) the last name after the first name, unless it's followed by the last name already. This looks similar, but uses a positive lookbehind as well:
(?<=Milan)(?! Vasic)
You can replace this by just " Vasic" (note the space at the start of the string):
String.replaceAll("(?<=Milan)(?! Vasic)", " Vasic")
You can try those things out here for example.