In Java, and it seems in a few other languages, backreferences in the pattern are preceded by a backslash (e.g. \1
, \2
, \3
, etc), but in a replacement string they preceded by a dollar sign (e.g. $1
, $2
, $3
, and also $0
).
Here's a snippet to illustrate:
System.out.println(
"left-right".replaceAll("(.*)-(.*)", "\\2-\\1") // WRONG!!!
); // prints "2-1"
System.out.println(
"left-right".replaceAll("(.*)-(.*)", "$2-$1") // CORRECT!
); // prints "right-left"
System.out.println(
"You want million dollar?!?".replaceAll("(\\w*) dollar", "US\\$ $1")
); // prints "You want US$ million?!?"
System.out.println(
"You want million dollar?!?".replaceAll("(\\w*) dollar", "US$ \\1")
); // throws IllegalArgumentException: Illegal group reference
Questions:
$
for backreferences in replacement strings unique to Java? If not, what language started it? What flavors use it and what don't?Is the use of $ for backreferences in replacement strings unique to Java?
No. Perl uses it, and Perl certainly predates Java's Pattern
class. Java's regex support is explicitly described in terms of Perl regexes.
For example: http://perldoc.perl.org/perlrequick.html#Search-and-replace
Why is this a good idea?
Well obviously you don't think it is a good idea! But one reason that it is a good idea is to make Java search/replace support (more) compatible with Perl's.
There is another possible reason why $
might have been viewed as a better choice than \
. That is that \
has to be written as \\
in a Java String literal.
But all of this is pure speculation. None of us were in the room when the design decisions were made. And ultimately it doesn't really matter why they designed the replacement String syntax that way. The decisions have been made and set in concrete, and any further discussion is purely academic ... unless you just happen to be designing a new language or a new regex library for Java.