2

I want to replace ";" with "\n" except when it's escaped with a leading '\'. I haven't figured out the correct regex.

Here is what I have:

String s = "abc;efg\\;hij;pqr;xyz\\;123"
s.replaceAll("\\[^\\\\];", "\\\\n");

I'd expect the above string to be replaced with "abc\nefg\;hij;pqr;xyz\;123"

6
  • just s.replace("\\;", "\n"); Commented Apr 5, 2016 at 3:42
  • I don't want to replace \; with \n. Only the semicolons with new line. I fixed the regex above. Commented Apr 5, 2016 at 3:48
  • So, @DarthNinja, when you said "I want to replace '\;' with '\n'" -- you didn't mean that...is that right? Ask the question you mean, please. Commented Apr 5, 2016 at 3:53
  • @Darth what about the other semicolons - after "hij" and "pqr"? Or do you only want the first semicolon to be replaced? Commented Apr 5, 2016 at 3:53
  • All unescaped semicolons to be replaced with new line. Any \; should be excluded. Commented Apr 5, 2016 at 3:55

1 Answer 1

2

Use a negative look behind:

s = s.replaceAll("(?<!\\\\);", "\n");

The expression (?<!\\) (coded as a java string literal "(?<!\\\\)") means "the previous character should not be a backslash"


Test code:

String s = "abc;efg\\;hij;pqr;xyz\\;123";
s = s.replaceAll("(?<!\\\\);", "\n");
System.out.println(s);

Output:

abc
efg\;hij
pqr
xyz\;123
Sign up to request clarification or add additional context in comments.

Comments

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.