【问题标题】:How to replace all matched text with dynamic group?如何用动态组替换所有匹配的文本?
【发布时间】:2014-06-22 07:35:29
【问题描述】:

如果我有一个String="#1 and #2",一个Map={"1":"a", "2":"b"},什么我打算做的是将#x 替换为Map(x) 评估的值,其结果应该是“a and b”

我的代码如下:

Map<String, String> map = new HashMap<String, String>();
    map.put("1", "a");
    map.put("2", "b");
    String s = "#1 and #2";
    Pattern p = Pattern.compile("#(.*?)(\\s|$)");
    Matcher m = p.matcher(s);
    while(m.find())        {
        s = m.replaceFirst(m.group(1));
        System.out.println(s);
}

但是输出是无限的,比如:

1and #2
2and #2
2and #2
2and #2
...
...

谁能给我一个关于这个现象的解释,并给我一个正确的解决我的问题的方法?非常感谢!

【问题讨论】:

  • 谢谢兄弟,这有帮助。但是你能解释一下为什么我的代码会以无限循环告终吗? @TheLostMind
  • 正则表达式部分错误..您正在通过在匹配器上调用 replaceFirst 来替换 s。

标签: java regex


【解决方案1】:

将您的正则表达式模式更改为 #(\d+) 以使其简单。

示例代码 1:(使用 String#replaceAll()

Map<String, String> map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
String s = "#1 and #2";
Pattern p = Pattern.compile("#(\\d+)");
Matcher m = p.matcher(s);
while (m.find()) {
    String match = m.group(1);
    s = s.replaceAll("#"+match, map.get(match));
}
System.out.println(s);

示例代码 2:(使用 Matcher#appendReplacement()

Map<String, String> map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
String s = "#1 and #2";
Pattern p = Pattern.compile("#(\\d+)");
Matcher m = p.matcher(s);
StringBuffer buffer = new StringBuffer();
while (m.find()) {
    m.appendReplacement(buffer, map.get(m.group(1)));
}
System.out.println(buffer);

请查看Matcher's documentation,其中详细介绍了更多内容。

Java Regex Replace with Capturing Group 的帖子可能会帮助您更好地理解它。

【讨论】:

    【解决方案2】:
        Map<String, String> map = new HashMap<String, String>();
        map.put("1", "a");
        map.put("2", "b");
        String s = "#1 and #2";
        String result = null ;
        Pattern p = Pattern.compile("#(\\d+).*#(\\d)");
        Matcher m = p.matcher(s);
        if(m.find()){
           result = s.replaceFirst("#\\d+", map.get(m.group(1)));
           result = result.replaceFirst("#\\d+", map.get(m.group(2)));
        }
        System.out.println(result);
    

    【讨论】:

      猜你喜欢
      • 2016-06-17
      • 2021-12-24
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2012-05-01
      • 2021-12-11
      • 2020-06-23
      相关资源
      最近更新 更多