我有如下所示的字符串。
$Trap:com.oss.Event(description matches "abc") 在上面的字符串中,通用部分是$Trap:com.oss.Event(<Any string>)。
当我遇到上面的字符串时,我需要替换为下面的字符串。
$Trap:com.oss.Event(description matches "abc") from entry-point "EventStream".为了实现上述目的,我在java中使用了以下逻辑。
String stmt= $Trap:com.oss.Event(description matches "abc")
if(stmt.matches(".*\\.Event(.*).*")&& s.equals(""))
{
stmt+=" from entry-point "+"ABCStream";
}但是,当字符串如下所示时,上述逻辑并不能按预期工作。
stmt="$Trap:com.oss.Event(description matches "abc") or $Trap:com.oss.Event(description matches "cde");我需要使用正则表达式生成以下相应的字符串。
$Trap:com.oss.Event(description matches "abc") from entry-point "ABCStream" or $Trap:com.oss.Event(description matches "cde") from entry-point "ABCStream"请提供一些指针来实现相同的目标。
发布于 2011-09-29 23:11:16
下面的Java代码可以工作:
String stmt = "$Trap:com.oss.Event(description matches \"abc\")"
+ " or $Trap:com.oss.Event(description matches \"cde\")";
Pattern p = Pattern.compile(".*?\\.Event\\(.*?\\)");
String res = p.matcher(stmt).replaceAll("$0 from entry-point \"ABCStream\"");
System.err.println(res);并产生以下结果:
$Trap:com.oss.Event(description matches "abc") from entry-point "ABCStream" or $Trap:com.oss.Event(description matches "cde") from entry-point "ABCStream"您需要在regexp中引用特殊字符,例如圆括号,也可以使用惰性匹配,即*?$0表示找到的匹配组。
如果您重复执行此替换操作,则使用Pattern.compile()将节省一些性能。
发布于 2011-09-29 23:22:19
这样做是这样的:
public class A {
public static void main(String[] args) {
String stmt="$Trap:com.oss.Event(description matches \"abc\") or $Trap:com.oss.Event(description matches \"cde\")";
System.out.println(stmt);
System.out.println(stmt.replaceAll("(\\$Trap:com.oss.Event\\([^)]*\\))", "$1 from entry-point \"ABCStream\""));
}
}正如您所看到的,您必须对一些符号进行双重转义。第一个和最后一个括号用于对正则表达式进行分组,您可以使用"$1“打印该组。
并获得以下输出:
$Trap:com.oss.Event(description matches "abc") or $Trap:com.oss.Event(description matches "cde")
$Trap:com.oss.Event(description matches "abc") from entry-point "ABCStream" or $Trap:com.oss.Event(description matches "cde") from entry-point "ABCStream"https://stackoverflow.com/questions/7599361
复制相似问题