noahy noahy - 24 days ago 5
Java Question

How to use beginning and endline markers in regex for Java String?

Why doesn't the following change the text for me in Android?

String content = "test\n=test=\ntest";
content = content.replaceAll("^=(.+)=$", "<size:large>$1</size:large>")


It returns the original value with no changes. I would expect it to replace the middle
=test=
with
<size:large>test</size:large>


What am I missing here?

Edit: Okay, I understand why
^
and
$
don't work. The point is that I need something that matches text both at the beginning and end of a line, e.g. a line that contains only "=some text=". Most of the answers given aren't sufficient, for the following reasons:

=(.+)=
doesn't have anything to do with line endings, so matches any line with two
=
in it that are not side by side.

.*=(.+)=.*
matches the whole line, but has the same problem as the previous

\n=(.+)=\n
gets closer, but won't match two lines in a row (e.g.
test\n=test=\n=test=\ntest
) It also won't match an instance on the first or last line

(?<=\n)=(.+)=(?=\n)
almost works, but again won't match an instance on the first or last line

(?<!.)=(.+)=(?!.)
is the only one that seems will actually match every line that starts and ends with
=
, for example, but $1 contains both the replacement and the original string.

content = content.replaceAll("(?<=(\n|^))=(.+)=(?=(\n|$))", "<size:large>$2</size:large>");
is the only answer that seems to actually do what it should.

Answer

Your original regex works fine if you turn on multiline mode, using (?m):

content = content.replaceAll("(?m)^=(.+)=$", "<size:large>$1</size:large>");

Now ^ and $ do indeed match at line boundaries.

Comments