简体   繁体   中英

Replace string for exact match with conditions

Sample string

astabD (tabD) tabD .tabD tabD. (tabD tabD)

I need to replace tabD with something like temp.tabD for every of the occurrence in the above string except the first and second one.

For this I tried replaceAll with word boundary

str.replaceAll("\\b"+ "tabD" + "\\b"," temp.tabD "))

Works except for the second occurrence. Would appreciate any help since '(' and ')' are also keywords and only the occurrence of both have to be ignored.

You may use

.replaceAll("\\b(?<!\\((?=\\w+\\)))tabD\\b", "")

Or, if tabD comes in from user input:

String s = "astabD (tabD) tabD .tabD tabD. (tabD tabD)";
String word = "tabD";
String wordRx = Pattern.quote(word);
s = s.replaceAll("(?<!\\w)(?<!\\((?=" + wordRx + "\\)))" + wordRx + "(?!\\w)", "");

See the regex demo .

Details

  • \\b - a word boundary ( (?<!\\w) is an unambiguous left word boundary)
  • (?<!\\((?=\\w+\\))) - a negative lookbehind that fails the match if right before the current location there is a ( that is followed with 1+ word chars ( \\w+ is required to match the tabD word) followed with ) ( NOTE : If your IDE tells you the + is inside a lookbehind, it is the IDE bug since the + is in a lookahead here and + / * quantifiers are allowed in lookaheads)
  • tabD - the word to find
  • \\b - a word boundary ( (?!\\w) is an unambiguous right word boundary)

Java demo :

String s = "astabD (tabD) tabD .tabD tabD. (tabD tabD)";
System.out.println(s.replaceAll("\\b(?<!\\((?=\\w+\\)))tabD\\b", ""));
// => astabD (tabD)  . . ( )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM