How to not replace when preceded with some characters using String's replaceAll

被刻印的时光 ゝ 提交于 2019-12-02 06:45:59

问题


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.


回答1:


I think this will give you a hint

String str = "word3.word1.word2.word1";
str.replaceAll("word3.word1", "word3.wordX1").replaceAll("word1", "word2").replaceAll("wordX1", "word1");



回答2:


Use regular expressions with negative lookbehind: (?<!word3\\.)word1




回答3:


I don't want to replace word1 if it's preceded by word3.

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:

String word1 = "word1";
String word2 = "word2";
String word3 = "word3.";

String regex = String.format("(?<!%s)%s", Pattern.quote(word3),
                                          Pattern.quote(word1));

String input = "aaa word1 bbb word3.word1 ccc";

String result = input.replaceAll(regex, word2);

System.out.println(result);

Output:

aaa word2 bbb word3.word1 ccc

(first word1 is replaced, second word1 is not replaced since it is preceeded by word3.)




回答4:


i m assuming the following scenario

String word1 = "word1";
String word2 = "word2";
String word3 = "word3";
String mysentence = "word3.myname.word1";

programatically you do like this

int word1loc = mysentence.indexOf(word1);
int word2loc = mysentence.indexOf(word2);
int word3loc = mysentence.indexOf(word3);

if (word1loc> word3loc){
mysentence.replaceAll(word1,word2);
}

i believe it may help you ...!



来源:https://stackoverflow.com/questions/9803285/how-to-not-replace-when-preceded-with-some-characters-using-strings-replaceall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!