tonimaroni
tonimaroni

Reputation: 1093

Negate regular expression to exclude complete lines

ER430;000000000;
ADR03;000000020;
RID01;000000000;
RID02;000000000;

I have above content within a string including new lines. Now i want to cut the string so only lines with a leading 'R' are left. Result should be:

RID01;000000000;
RID02;000000000;

Unfortunately i didn't find the solution yet after some hours trying.. thanks for any help!!

Some of my tests:

 content = s.replaceAll("[^R].+;{1}.+;{1}", "");
 content = s.replaceAll("(?!R).*;{1}.*;{1}", "");
 content = s.replaceAll("(?!R)(.+;)(.+;)", "");

which all are not exactly bringing the solution..

Upvotes: 1

Views: 57

Answers (2)

Bohemian
Bohemian

Reputation: 424993

Use the multi line flag (?m), which makes ^ and $ match at newlines, and the DOTALL flag (?s), which makes dot match newlines:

str = str.replaceAll("(?sm)^[^R].*?(^|\\Z)", "");

The start is straightforward - a non-R char, then .*?^ will grab every char up to the start of the next line - including the newline char Adding an alternate ending of \Z caters for the last line being removed too.

See live demo that includes edge case of last line removal.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

If you use the anchors ^, $ in your code, you need to include the multiline (?m) modifier or DOTALL (?s) modifier.

String str = "ER430;000000000;\n" + 
        "ADR03;000000020;\n" + 
        "RID01;000000000;\n" + 
        "RID02;000000000;";
System.out.println(str.replaceAll("(?s)(?<=\n|^)[^R][^;\n]*?;[^;\n]*;(\n|$)", ""));

Output:

RID01;000000000;
RID02;000000000;

OR

System.out.println(str.replaceAll("(?m)(?<=\n|^)[^R][^;\n]*?;[^;\n]*;(\n|$)", ""));

Upvotes: 0

Related Questions