简体   繁体   中英

Java regex: replace a substring that is preceded by '$'

I would like to know if there is a proper way to replace a substring that is preceded by $ . For instance, if we have strings that look like:

String s = "something variable = $firstname something something"; or

String s = "something foo($firstname) something else";

I would like to replace all occurences of a "variable"(ie is preceded by $ ), in this case, $firstname with 'x' (including the single quotes). So we should end up with the result:

String s = "something variable = 'x' something something"; or

String s = "something foo('x') something else";

But I'm not sure how to write a proper regex that can do this.

try something like \$[a-zA-Z]+

$ followed by one or more characters in az,AZ

String s = "something variable = $firstname something something";

matches $firstname

String s = s.replaceAll("<your regex>", "'x'");

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