Java replaceAll() only replaces one instance

396 views Asked by At

I would like to use string.replaceAll() to replace all sequences of characters beginning with '@', '$', or ':', and ending with a ' '(space). So far I have this:

string = string.replaceAll("[@:$]+.*?(?= )", "ZZZZ");

However, the regex used only replaces the first instance that meets the above criteria. So, given the string:

"SELECT title FROM Name WHERE nickname = :nickname AND givenName = @givenName AND familyName = $familyName"

Current (incorrect) output:

"SELECT title FROM Name WHERE nickname = ZZZZ AND givenName = @givenName AND familyName = $familyName"

Desired output:

"SELECT title FROM Name WHERE nickname = ZZZZ AND givenName = ZZZZ AND familyName = ZZZZ"

How can I edit the regex to produce the desired output?

2

There are 2 answers

1
maraca On BEST ANSWER

As mentioned you can use the following statement:

string = string.replaceAll("[@:$]+[^ ]*", "ZZZZ");

[^...] matches all characters except those followed by ^.

Possible applications:

  1. One time processing of human-written files (need to control the outcome, there might be Strings containing @:$

  2. Maybe modifying some debug output so it can be executed in a DBMS

It might be safer to restrict to something like [a-zA-Z0-9_.]* instead of [^ ]*.

0
Federico Piazza On

If you want to remove the words starting with those characters then you can use this code:

string = string.replaceAll("[@:$]+\\w+", "ZZZZ");

Working demo

enter image description here