一次替换多个子串 [英] Replace multiple substrings at once

查看:123
本文介绍了一次替换多个子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个文件,其中包含一些文字。其中有子字符串,如substr1,substr2,substr3等。我需要用其他一些文本替换所有这些子串,例如repl1,repl2,repl3。在Python中,我会创建一个这样的字典:

Say I have a file, that contains some text. There are substrings like "substr1", "substr2", "substr3" etc. in it. I need to replace all of those substrings with some other text, like "repl1", "repl2", "repl3". In Python, I would create a dictionary like this:

{
 "substr1": "repl1",
 "substr2": "repl2",
 "substr3": "repl3"
}

并创建用'|'连接键的模式,然后用 re.sub 函数替换。
在Java中是否有类似的简单方法?

and create the pattern joining the keys with '|', then replace with re.sub function. Is there a similar simple way to do this in Java?

推荐答案

这就是你的Python建议转换为Java:

This is how your Python-suggestion translates to 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






this方法做了同时(即立刻)替换。即,如果您碰巧有


This approach does a simultanious (i.e. "at once") replacement. I.e., if you happened to have

"a" -> "b"
"b" -> "c"

然后这种方法会给出a b - > bc而不是答案表明你应该将几个电话链接到替换 replaceAll 哪个会给cc

then this approach would give "a b" -> "b c" as opposed to the answers suggesting you should chain several calls to replace or replaceAll which would give "c c".

(如果你概括了这种以编程方式创建正则表达式的方法,请确保每个单独的搜索词 Pattern.quote Matcher.quoteReplacement 每个替换词。)

(If you generalize this approach to create the regexp programatically, make sure you Pattern.quote each individual search word and Matcher.quoteReplacement each replacement word.)

这篇关于一次替换多个子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆