0

given the following expression:

Pattern.compile("^Test.*\n").matcher("Test 123\nNothing\nTest 2\n").replaceAll("foo\n")

This yields:

"foo\nNothing\nTest 2\n"

for me. I expected that the last line is also replaced to foo\n since there is a linebreak immediately before Test 2 in the input string.

Why is doesn't the regex match there?

SpaceTrucker
  • 13,377
  • 6
  • 60
  • 99

2 Answers2

1

You have to add the multiline flag to the pattern: Pattern.MULTILINE.

Pattern.compile("^Test.*\n", Pattern.MULTILINE).matcher("Test 123\nNothing\nTest 2\n").replaceAll("foo\n")

By Default the match is only single line. For more Informations see the javadoc

Jens
  • 67,715
  • 15
  • 98
  • 113
1

At the beginning of your regex you have a ^ sign which normally anchors the regex to the beginning of a tested string. You need to specify multiline regex option (Oracle Documentation link) to make it apply to start of each line instead.

Try this (I have split the lines for legibility, feel free to oneline it back):

Pattern.compile("^Test.*\n", Pattern.MULTILINE)
       .matcher("Test 123\nNothing\nTest 2\n")
       .replaceAll("foo\n")

Unfortunately I do not have Java environment set up at the moment, so I'm unable to check this by myself.

Asunez
  • 2,327
  • 1
  • 23
  • 46