Java Regex替换为捕获组

use*_*ser 2 java regex

可能重复:
Java Regex替换为捕获组

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

例:

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

而且我想用$ 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();
}
Run Code Online (Sandbox Code Playgroud)

它抛出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();
}
Run Code Online (Sandbox Code Playgroud)

工作正常,但我不能改变$ 1 :(

EDIT2:

现在,它的工作:)

Ala*_*ore 16

几年前Elliott Hughes在他的博客上发布了这个问题的最终解决方案.Elliott不断向在线版本中的其他类引入无意义的依赖项,因此我将在此发布一个独立版本(依赖项仅在main()方法的测试中).

import java.util.regex.*;

/**
 * A Rewriter does a global substitution in the strings passed to its
 * 'rewrite' method. It uses the pattern supplied to its constructor, and is
 * like 'String.replaceAll' except for the fact that its replacement strings
 * are generated by invoking a method you write, rather than from another
 * string. This class is supposed to be equivalent to Ruby's 'gsub' when
 * given a block. This is the nicest syntax I've managed to come up with in
 * Java so far. It's not too bad, and might actually be preferable if you
 * want to do the same rewriting to a number of strings in the same method
 * or class. See the example 'main' for a sample of how to use this class.
 *
 * @author Elliott Hughes
 */
public abstract class Rewriter
{
  private Pattern pattern;
  private Matcher matcher;

  /**
   * Constructs a rewriter using the given regular expression; the syntax is
   * the same as for 'Pattern.compile'.
   */
  public Rewriter(String regex)
  {
    this.pattern = Pattern.compile(regex);
  }

  /**
   * Returns the input subsequence captured by the given group during the
   * previous match operation.
   */
  public String group(int i)
  {
    return matcher.group(i);
  }

  /**
   * Overridden to compute a replacement for each match. Use the method
   * 'group' to access the captured groups.
   */
  public abstract String replacement();

  /**
   * Returns the result of rewriting 'original' by invoking the method
   * 'replacement' for each match of the regular expression supplied to the
   * constructor.
   */
  public String rewrite(CharSequence original)
  {
    this.matcher = pattern.matcher(original);
    StringBuffer result = new StringBuffer(original.length());
    while (matcher.find())
    {
      matcher.appendReplacement(result, "");
      result.append(replacement());
    }
    matcher.appendTail(result);
    return result.toString();
  }



  public static void main(String... args) throws Exception
  {
    String str = "12 54 1 65";

    // anonymous subclass
    Rewriter tripler = new Rewriter("(\\d{1,2})")
    {
      public String replacement()
      {
        int intValue = Integer.valueOf(group(1));
        return String.valueOf(intValue * 3);
      }
    };
    System.out.println(tripler.rewrite(str));

    // inline subclass
    System.out.println(new Rewriter("(\\d{1,2})")
    {
      public String replacement()
      {
        int intValue = Integer.valueOf(group(1));
        return String.valueOf(intValue * 3);
      }
    }.rewrite(str));

  }
}
Run Code Online (Sandbox Code Playgroud)