2

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"?

MrLore
  • 3,759
  • 2
  • 28
  • 36
hasanghaforian
  • 13,858
  • 11
  • 76
  • 167

3 Answers3

3

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.

hasanghaforian
  • 13,858
  • 11
  • 76
  • 167
gexicide
  • 38,535
  • 21
  • 92
  • 152
3

$ means end of input, not end of line.

However, this is easily solved using the "multi line" flag; change your regex to add (?m) at the front:

String regex = "(?m)$";

The multi line flag makes caret ^ and dollar $ match start and end of lines

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

It's definitive for the end of your input. If you have newline literals in your input, the $ will not match them.

If you want to match every newline, something like:

str.replaceAll("(\r\n|$)", "*$1");

might work.

Rogue
  • 11,105
  • 5
  • 45
  • 71