Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

java - Backreferences Syntax in Replacement Strings (Why Dollar Sign?)

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:

  • Is the use of $ for backreferences in replacement strings unique to Java? If not, what language started it? What flavors use it and what don't?
  • Why is this a good idea? Why not stick to the same pattern syntax? Wouldn't that lead to a more cohesive and an easier to learn language?
    • Wouldn't the syntax be more streamlined if statements 1 and 4 in the above were the "correct" ones instead of 2 and 3?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...