我有一个字符串,如下所示
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");
我想使用贪婪匹配使用正则表达式替换字符串。 请提供一些指示,以实现相同的目标。
答案 0 :(得分:1)
简单的解决方案不要打扰使用正则表达式包含的字符串方法。 创建一个Scanner对象,用于解析行的字符串行,并将结果添加到String缓冲区。
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);
}
答案 1 :(得分: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());
}
}
输出
当
$ Alarm:com.abc.Alarm(description ==“abc”)
然后
logger.info(“报警说明”)
当
输入点“AlarmStream”$ Alarm:com.abc.Alarm(description ==“abc”)
然后
logger.info(“报警说明”)