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

Viewed 47

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"(i.e 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.

1 Answers

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

$ followed by one or more characters in a-z,A-Z

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

matches $firstname

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