即使您的示例数据在"yyy" 之前显示"xxx",也没有指定"xxx" 是否在"yyy" 之前,反之亦然。您只需声明"special characters between the following String when only when they are between two words, BEGIN and END"。
我看到有一个Map<String, String>,其中键是您的“特殊”字符串,值是将替换“特殊”字符串的字符串。
遍历此映射并提供此映射的键:
String.format("BEGIN.*?(%s).*?END", kvp.getKey())
在本例中,它将产生两个正则表达式模式:
"BEGIN.*?(xxx).*?END"
"BEGIN.*?(yyy).*?END"
这会将您的“特殊”字符串捕获到捕获组 1,您将提供给 String.replace(),如下所示:
raw = raw.replace(matcher.group(), matcher.group().replace(matcher.group(1), kvp.getValue()));
matcher.group() 是整个匹配字符串BEGIN ... END 和matcher.group(1) 将是xxx 或yyy
把这一切放在一起,你就有了:
public static void main(String[] args) throws Exception {
Map<String, String> replacerMap = new HashMap() {{
put("xxx", "CCC");
put("yyy", "DDD");
}};
String raw = "John Doe xxx Amazing man BEGIN reference xxx yes yyy indeed this is true xxx no yyy END , so this xxx does not change";
System.out.println("Before: ");
System.out.println(raw);
System.out.println();
for (Map.Entry<String, String> kvp : replacerMap.entrySet()) {
Matcher matcher = Pattern.compile(String.format("BEGIN.*?(%s).*?END", kvp.getKey())).matcher(raw);
if (matcher.find()) {
raw = raw.replace(matcher.group(), matcher.group().replace(matcher.group(1), kvp.getValue()));
}
}
System.out.println("After: ");
System.out.println(raw);
}
结果:
Before:
John Doe xxx Amazing man BEGIN reference xxx yes yyy indeed this is true xxx no yyy END , so this xxx does not change
After:
John Doe xxx Amazing man BEGIN reference CCC yes DDD indeed this is true CCC no DDD END , so this xxx does not change