Java正则表达式替换为捕获组

有什么方法可以用捕获组的已修改内容替换正则表达式?


例:


Pattern regex = Pattern.compile("(\\d{1,2})");

Matcher regexMatcher = regex.matcher(text);

resultString = regexMatcher.replaceAll("$1"); // *3 ??

我想用$ 1乘以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:找不到匹配项



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 :(




慕婉清6462132
浏览 1306回答 3
3回答

侃侃尔雅

伯爵的答案为您提供了解决方案,但我想我要补充一下造成您问题的原因IllegalStateException。您在调用时group(1)无需先调用匹配操作(例如find())。如果您只是在使用$1,replaceAll()则不需要此操作,因为这是匹配操作。
打开App,查看更多内容
随时随地看视频慕课网APP