I need to replace some words in a text, but I need to put conditions in the replacement strategy as follows:
I want to replace word1 with word2:
String word1 = "word1";
String word2 = "word2";
but I don't want to replace word1 if it's preceded by word3 which is:
String word3 = "word3."; //with the dot at the ending
That is if the text is word3.word1 I don't want to touch it.
But I can't seem to handle that with word boundaries using String's replaceAll
method.
EDIT:
And also I don't want to change if word1 has a prefix or suffix of "-" character i.e. -word1 or word1- or -word1-
Any help would be appreciable.
i m assuming the following scenario
programatically you do like this
i believe it may help you ...!
I think this will give you a hint
Use regular expressions with negative lookbehind:
(?<!word3\\.)word1
You need to use a negative lookbehind.
Unless you want to hard-code the words you probably want to use
Pattern.quote
as well.Here's some example code:
Output:
(first
word1
is replaced, secondword1
is not replaced since it is preceeded byword3.
)