Java Regex替换为捕获组 [英] Java Regex Replace with Capturing Group

查看:107
本文介绍了Java Regex替换为捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用修改后的捕获组内容替换正则表达式?

Is there any way to replace a regexp with modified content of capture group?

示例:

Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher(text);
resultString = regexMatcher.replaceAll("$1"); // *3 ??

我想用$ 1替换所有出现次数乘以3。

And I'd like to replace all occurrence with $1 multiplied by 3.

编辑

看起来有些不对劲:(

如果我使用

Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
    String resultString = regexMatcher.replaceAll(regexMatcher.group(1));
} catch (Exception e) {
    e.printStackTrace();
}

抛出IllegalStateException:找不到匹配项

It throws an IllegalStateException: No match found

但是

Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
    String resultString = regexMatcher.replaceAll("$1");
} catch (Exception e) {
    e.printStackTrace();
}

工作正常,但我无法更改$ 1 :(

works fine, but I can't change the $1 :(

编辑

现在,它正在工作:)

推荐答案

怎么样:

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

要获得第一场比赛,请使用 #find( )。之后,您可以使用 #group(1)来引用第一个匹配,并将第一个匹配值替换所有匹配值乘以3.

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

如果您想用该匹配值替换每个匹配的值乘以3:

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

您可能想查看 Matcher 的文档,其中和详细介绍了更多的东西。

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

这篇关于Java Regex替换为捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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