我可以用Java正则expression式replace组吗?

我有这个代码,我想知道,如果我可以在Java正则expression式中只replace组(不是所有模式)。 码:

//... 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(...)捕获子序列。 我假设你想用string“数字”replace第一组,用第一组的值replace第二组。

 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 $2$1"); // number 46 } 

考虑(\D+)第二组而不是(.*)*是一个贪婪的匹配器,并会首先消耗最后一位数字。 当匹配到最后一位数字之前,匹配器将不得不回溯到最终(\d)没有匹配的地方。

你可以使用Matcher#start(group)Matcher#end(group)来build立一个通用的replace方法:

 public static String replaceGroup(String regex, String source, int groupToReplace, String replacement) { return replaceGroup(regex, source, groupToReplace, 1, replacement); } public static String replaceGroup(String regex, String source, int groupToReplace, int groupOccurrence, String replacement) { Matcher m = Pattern.compile(regex).matcher(source); for (int i = 0; i < groupOccurrence; i++) if (!m.find()) return source; // pattern not met, may also throw an exception here return new StringBuilder(source).replace(m.start(groupToReplace), m.end(groupToReplace), replacement).toString(); } public static void main(String[] args) { // replace with "%" what was matched by group 1 // input: aaa123ccc // output: %123ccc System.out.println(replaceGroup("([az]+)([0-9]+)([az]+)", "aaa123ccc", 1, "%")); // replace with "!!!" what was matched the 4th time by the group 2 // input: a1b2c3d4e5 // output: a1b2c3d!!!e5 System.out.println(replaceGroup("([az])(\\d)", "a1b2c3d4e5", 2, 4, "!!!")); } 

在这里检查在线演示

添加第三组,添加parens .* ,然后用"number" + m.group(2) + "1"replace子序列。 例如:

 String output = m.replaceFirst("number" + m.group(2) + "1"); 

您可以使用matcher.start()和matcher.end()方法获取组位置。 所以使用这个职位你可以轻松地replace任何文本。