2016-04-26 27 views
0

刪除一個正則表達式匹配我有一個字符串,如下所示:如何從源在java中

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 

我想從Bolus Exposure (Impedance)總刪除對

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

一切我的代碼是

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,""); 
    } 
} 

然而,字符串s與此前相同。我如何從源字符串中刪除匹配項?如果這是不可能的,我怎樣才能創建一個新的字符串,但只有匹配

回答

1

字符串在Java中是不可變的,請更改以下代碼以進行賦值。

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

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

爲什麼不使用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" 
); 
0

儘量簡單

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

注:(?s)是DOTALL選項。