And*_*huk 8 java regex replace
假设我有一个包含一些文本的文件.其中有子字符串,如"substr1","substr2","substr3"等.我需要用其他一些文本替换所有这些子串,例如"repl1","repl2","repl3".在Python中,我会创建一个这样的字典:
{
"substr1": "repl1",
"substr2": "repl2",
"substr3": "repl3"
}
Run Code Online (Sandbox Code Playgroud)
并创建用'|'连接键的模式,然后用re.sub函数替换.在Java中有没有类似的简单方法?
aio*_*obe 14
这就是你的Python建议转换为Java的方式:
Map<String, String> replacements = new HashMap<String, String>() {{
put("substr1", "repl1");
put("substr2", "repl2");
put("substr3", "repl3");
}};
String input = "lorem substr1 ipsum substr2 dolor substr3 amet";
// create the pattern joining the keys with '|'
String regexp = "substr1|substr2|substr3";
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(input);
while (m.find())
m.appendReplacement(sb, replacements.get(m.group()));
m.appendTail(sb);
System.out.println(sb.toString()); // lorem repl1 ipsum repl2 dolor repl3 amet
Run Code Online (Sandbox Code Playgroud)
这种方法可以进行同步(即"立即")替换.即,如果你碰巧有
"a" -> "b"
"b" -> "c"
Run Code Online (Sandbox Code Playgroud)
然后这种方法会给出"a b" -> "b c"答案,而不是答案表明你应该链接几个replace或replaceAll哪个会给出"c c".
(如果您推广这种方法以编程方式创建正则表达式,请确保Pattern.quote每个单独的搜索词和Matcher.quoteReplacement每个替换词.)