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

查看:106
本文介绍了我可以替换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天全站免登陆