Home > Enterprise >  regex for substring followed by any character
regex for substring followed by any character

Time:04-06

String str ="abcdef should be replaced but abc should not be replaced";

Wanna replace "abcdef" to "pqrdef" in above string in java. But while using replaceAll method, it replaces the second occurence of abc as well. str=str.replaceAll("abc","pqr");

The expected output is :- pqrdef should be replaced but abc should not be replaced

The current output is :- pqrdef should be replaced but pqr should not be replaced

Scenario 2:-

String str1="The belgian' & europians prepare awesome Belgian chocolate"; in this case as well, wanna replace the first occurence of "&" to &, but as there are two occurrences of "&" in the provided string so both got replaced.

CodePudding user response:

replaceAll actually takes a regex, hence you can use something like:

str=str.replaceAll("abc[^\\s]","pqr");

above exactly means to replace "abc" when there is no space after it with the replacement string of "pqr".

You can see more examples here: https://www.vogella.com/tutorials/JavaRegularExpressions/article.html

CodePudding user response:

Explanation:

  • (?=whatever) is used to create a lookahead that isn't part of the capture
  • \w is the escape code for "word" characters (you could also use [a-zA-Z] or whatever else you want to allow after the "abc")

For "abcdef abc abc" to be "pqrdef abc abc" (what you appear to be asking for):

str = str.replaceAll("abc(?=\\w)", "pqr")

PS - Here is the Java documentation for Pattern which explains the regex syntax.

  • Related