regex - How to replace a specific occurrence of a sub-string in a string and ignoring incomplete matches in java? -


this question has answer here:

in application i'm giving dictionary word suggestions , replacing selected word suggested word using .replaceall(). replacing every sub string in entire string

for example in string,

string sentence = "od , not odds sample sam. not odinary"; 

if suggest first word odd .replaceall() replace every occurrence of od odd hence affecting fourth word oddds , changing sentence to

sentence.replaceall("od", "odd");    //sentence string becomes sentence ="odd , not oddds sample sam. not oddinary" 

replacing od odd has affected other words have od characters in them.

can 1 me better aproach?

use regex. example "\bod\b" match od whole word. \b word boundary, meaning either start or end of word (whether ends dot or whitespace or else).

the replaceall method can take in regex, if need more power can @ matcher class.

string replace_word = "od" sentence.replaceall("\\b" + replace_word + "\\b", "odd"); 

will give correct answer. \ tells java want write \ instead of \b (it first parses string, , parses string regex).


Comments