I am new to java regex.I saw this in Docs:
$ The end of a line
But when I try this snippet:
String str = "firstline\r\nsecondline";
String regex = "$";
System.out.println(str.replaceAll(regex, "*"));
I guess result will be:
firstline*
secondline*
But I see this result:
firstline
secondline*
It seems that it $
only matches the end of a String. So why do the docs say it matches "The end of a line"?
You must enable multiline mode, then $
will match both, the end of a line and the end of the input:
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#MULTILINE
i.e.:
Pattern.compile("$",Pattern.MULTILINE);
You can also use the flag expression (?m)
, i.e.:
Pattern.compile("(?m)$");
The oracle docs you cite are really quite imprecise here. The documentation of the pattern class (link above) is more precise and should be your reference for Java RegExs.