How to write dollar sign in regexp replacement string?

I've tried with escape character \$ and with $$ (as I've seen on the web), but none would be accepted as a replacement string in regexp search/replace operation: I always get 'You have entered malformed replacement string'....

please help!!!

/nodje

5 comments

There is a regexp plugin which allows you to easily test the regular expressions on some dummy text.

btw: in there the escape combination \$ seems to work.

HTH

0

\$ is correct. The '$' needs to be escaped since Java uses that as the escape character for a capturing group. However, when you use the \$ in a Java String, you need to escape the back slash. So it becomes:
$

So to replace "dollars" with "$", you would have:

String replaced = original.replaceAll("dollars", "
$");

Or for a more sophisticated example, to replace any n dollars with $n you would have:

String original = "Cost is 200 dollars";
String replaced = original.replaceAll("(+) dollars", "
$$1");
System.out.println(original);
System.out.println(replaced);

+
Output:
Cost is 200 dollars
Cost is $200
+

Viva Regex!

Message was edited by:
Mark Vedder - added output

0

Regex is dead!
Long live Regex!!

-or-

Regular expressions: You can't live with 'em, you can't live without 'em...


RRS

0

yeah!
it works...
i'm so happy :)

0

Please sign in to leave a comment.