Sebastian Zeki
Sebastian Zeki

Reputation: 6874

how to remove a regex match from the source in java

I have a string as follows:

Acid Exposure (pH)      Total
            Total   Normal
        Clearance pH  :  Channel 7
        Number of Acid Episodes 6   
        Time    48.6 min    
        Percent Time    20.3%   
        Mean Acid Clearance Time    486 sec 
        Longest Episode 24.9 min

        Gastric pH  :  Channel 8
        Time pH<4.0 208.1 min
        Percent Time    86.7%   


    Postprandial Data (Impedance)       Total
            Total   Normal
        Acid Time   2.9 min 
        Acid Percent Time   1.2%    
        Nonacid Time    11.6 min    
        Nonacid Percent Time    4.8%    
        All Reflux Time 14.5 min    
        All Reflux Percent Time 6.1%    
        Median Bolus Clearance Time 8 sec   
        Longest Episode 11.2 min
        NOTE:  Reflux episodes are detected by Impedance and categorized as acid or nonacid by pH

I want to remove everything from Bolus Exposure (Impedance) Total to

NOTE:  Reflux episodes are detected by Impedance and categorized as acid or nonacid by pH

My code is

Pattern goPP = Pattern.compile("Postprandial Data.*?Reflux episodes are detected by Impedance and categorized as acid or nonacid by pH",Pattern.DOTALL);
Matcher goPP_pattern = goPP.matcher(s);

while (goPP_pattern.find()) {
    for (String df:goPP_pattern.group(0).split("\n")) {
        s.replaceAll(df,"");
    }
}

however the string s is the same after this as before. How can I remove the match from the source string? If that's not possible, how can I create a new string with everything but the match

Upvotes: 0

Views: 49

Answers (3)

user4910279
user4910279

Reputation:

Try simply

s = s.replaceAll("(?s)Postprandial Data.*?Reflux episodes are detected by Impedance and categorized as acid or nonacid by pH", "");

note: (?s) is DOTALL option.

Upvotes: 0

Tamas Hegedus
Tamas Hegedus

Reputation: 29906

Why don't you just use String.replaceAll?

s = s.replaceAll(
  "Postprandial Data.*?Reflux episodes are detected by Impedance and categorized as acid or nonacid by pH",
  "Postprandial Data\nReflux episodes are detected by Impedance and categorized as acid or nonacid by pH"
);

Upvotes: 0

11thdimension
11thdimension

Reputation: 10633

Strings are immutable in Java, change following code for assignment.

s.replaceAll(df,""); // wrong, no op

s = s.replaceAll(df,"");//correct

Upvotes: 1

Related Questions