2011-08-25 22 views
0

我有一個字符串,如下如何使用正則表達式中使用的Java

when 
    $Event:com.abc.Event(description == "abc") 
    then 
    logger.info("description"); 

我需要使用以下

when 
    $Event:com.abc.Event(description == "abc") from entry-point "EventStream" 
    then 
    logger.info("description"); 

替換上面的字符串以同樣的方式時,我遇到

替換特定的字符串
when 
$Alarm:com.abc.Alarm(description == "abc") 
then 
logger.info("alarm description"); 

我需要改變如下

when 
$Alarm:com.abc.Alarm(description == "abc") from entry-point "AlarmStream" 
then 
logger.info("alarm description"); 

我想使用正則表達式使用貪婪匹配替換字符串。 請給我一些指示,以達到同樣的效果。

回答

1

簡單的解決方案不用麻煩正則表達式使用字符串方法包含代替。 製作一個Scanner對象,用於解析字符串行的行並將結果添加到字符串緩衝區。

if(line.contains("$Event:com.abc.Event(description == "abc")"){ 
    sb.append(line + "from entry-point \"EventStream\" "); 
} else if(line.contains("$Alarm:com.abc.Alarm(description == \"abc\")") { 
sb.append(line + "from entry-point \"AlarmStream\" "); 
}else { 
sb.append(line); 
} 
+0

感謝您的更新。但在我的情況下,問題是「.Event(」和「)」在第一種情況下,「.Alarm(」和「)」將保持不變,當部分,所以我不想去確切的字符串比較。 – mohan

+0

@gsr我已經爲您做出了一個新的答案,看看是否符合您的要求。 – Farmor

0

將使用正則表達式和測試類的新答案。

import java.util.Scanner; 


public class RegEx { 

public static void main(String[] args) { 
    String text = "when\n$Alarm:com.abc.Alarm(description == \"abc\")\nthen\nlogger.info(\"alarm description\")"; 
    System.out.println(text); 
    StringBuilder sb = new StringBuilder(); 
    Scanner scan = new Scanner(text); 
    while(scan.hasNextLine()){ 
     String line = scan.nextLine(); 
     if(line.matches(".*\\.Alarm(.*).*")){ 
      line+=" from entry-point \"AlarmStream\""; 
     } 
     sb.append(line+System.getProperty("line.separator")); 
    } 
    System.out.println(); // Nicer output 
    System.out.println(sb.toString()); 
} 

}

輸出

$報警:com.abc.Alarm(介紹== 「ABC」)

然後

logger.info(「報警描述」)

$報警:com.abc.Alarm(說明== 「ABC」),從入口點 「AlarmStream」

然後

logger.info( 「報警內容」)