我可以替换 Java 正则表达式中的组吗? [英] Can I replace groups in Java regex?

查看:24
本文介绍了我可以替换 Java 正则表达式中的组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,我想知道,我是否只能替换 Java 正则表达式中的组(不是所有模式).代码:

I have this code, and I want to know, if I can replace only groups (not all pattern) in Java regex. Code:

 //...
 Pattern p = Pattern.compile("(\d).*(\d)");
    String input = "6 example input 4";
    Matcher m = p.matcher(input);
    if (m.find()) {

        //Now I want replace group one ( (\d) ) with number 
       //and group two (too (\d) ) with 1, but I don't know how.

    }

推荐答案

使用 $n(其中 n 是数字)来引用 replaceFirst(...).我假设你想用文字字符串 "number" 替换第一组,用第一组的值替换第二组.

Use $n (where n is a digit) to refer to captured subsequences in replaceFirst(...). I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.

Pattern p = Pattern.compile("(\d)(.*)(\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
    // replace first number with "number" and second number with the first
    String output = m.replaceFirst("number $3$1");  // number 46
}

考虑第二组的 (D+) 而不是 (.*).* 是一个贪婪的匹配器,首先会消耗最后一位数字.当匹配器意识到最后的 (d) 没有任何可匹配时,它必须回溯,然后才能匹配到最后的数字.

Consider (D+) for the second group instead of (.*). * is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (d) has nothing to match, before it can match to the final digit.

这篇关于我可以替换 Java 正则表达式中的组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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