2

So I have read 2 strings from an xml file. The xml string is:

<regex code="bla[. ]?(.*)\n" replacement="cpe_ip_learning_table:\\n$1\\n "/>

This reads into two separate variables for a replaceAll call. i.e:

str = str.replaceAll(code, replacement);

However, even when I try a \n as a replacement instead of a \\n it still does not insert a newline.

I am using a DOM DocumentBuilder to read the XML file into two separate strings. I have tried using Matcher.quoteReplacement as well to no avail. Has anyone run into this issue and how have they solved it?

1 Answer 1

1

I've experienced this same behavior also, and the only way I found to fix it was by doing a replaceAll on the replacement string itself:

rep = replacement.replaceAll("\\\\n", "\n")
str = str.replaceAll(code, rep);

Strings returned by DOMDocument ignore newline (\n) constructs for some strange reason.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm curious why they do this though. Could it be because we use doc.normalize() ?
@bge0, doc.normalize doesn't appear to be the reason, for the behavior remains the same whether used or not. It's almost as if the replaceAll pattern expects literal newlines to be in the replacement string, which could only be represented by including a physical carriage return in the places you've got the construct \n (see here); that definitely doesn't seem right either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.