Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java best way for string find and replace?

Tags:

java

string

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!

like image 896
vaske Avatar asked Jan 12 '10 14:01

vaske


People also ask

How do I replace an entire string with another string in Java?

To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.

How do you replace a string after a specific character in Java?

Java String replace() method replaces every occurrence of a given character with a new character and returns a new string. The Java replace() string method allows the replacement of a sequence of character values. The Java replace() function returns a string by replacing oldCh with newCh.

How do you replace a word in a string in Java without using replace method?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.

Which method can be used to replace parts of a string?

replace() Return Value The replace() method returns a copy of the string where the old substring is replaced with the new substring. The original string is unchanged.


2 Answers

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.

like image 163
Joey Avatar answered Sep 23 '22 21:09

Joey


Another option:

"My name is Milan, people know me as Milan Vasic"     .replaceAll("Milan Vasic|Milan", "Milan Vasic")) 
like image 25
McDowell Avatar answered Sep 23 '22 21:09

McDowell