Search code examples
javaregexreplaceall

Java replaceAll() only replaces one instance


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?


Solution

  • 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 [^ ]*.