簡體   English   中英

模式匹配器未提供預期的輸出

[英]Pattern matcher is not giving expected output

我有下面的代碼。

String testdata = "%%%variable1%%% is not equal to %%%variable2%%%";
Pattern p = Pattern.compile("\\%%%(.*?)\\%%%");
Matcher m = p.matcher(testdata);
String variables = "";
int i = 0;
while (m.find()) {
    System.out.println(m.group());
    variables=m.group().replaceAll("%%%", "");
    System.out.println(variables);
    i++;
}

我正在嘗試在兩個%%%內打印字符串。 所以我期望下面的輸出:

%%%variable1%%% 
variable1 
%%%variable2%%% 
variable2

但是實際輸出是:

%%%variable1%%%
variable1
variable2
variable2

為什么會這樣呢? 這是什么問題?

您需要刪除i 沒有必要

while (m.find()) {
      System.out.println(m.group());
      String variables=m.group().replaceAll("%%%", "");
      System.out.println(variables);
}

Ideone演示

您也不需要replaceAll因為您所需要的已經在第一個捕獲組中

while (m.find()) {
     System.out.println(m.group());
     System.out.println(m.group(1));
}

Ideone演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM