简体   繁体   中英

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?

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

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

Working demo

在此输入图像描述

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

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