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

Java正则表达式替换为捕获组,java,regex,Java,Regex,可能重复: 有没有办法用捕获组的修改内容替换regexp 例如: Pattern regex = Pattern.compile("(\\d{1,2})"); Matcher regexMatcher = regex.matcher(text); resultString = regexMatcher.replaceAll("$1"); // *3 ?? 我想用1美元乘以3来代替所有发生的事情 编辑: 看起来有点不对劲:( 如果我使用 Pattern regex = Pattern.comp

可能重复:

有没有办法用捕获组的修改内容替换regexp

例如:

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();
}
它抛出一个非法状态异常:未找到匹配项

但是

工作正常,但我无法更改1美元:(

edit2:


现在,它可以工作了:)

不,你不能用正则表达式做这件事。正则表达式没有数值的概念,所以用数字做算术是不可能的(假设你想把“12 54 1 65”转换成“36 162 3 195”)

注意,对于某些语言和正则表达式实现,您可以这样做(Chris发布的Perl),但这不是正则表达式,尤其不是Java正则表达式。
你说你已经解决了这个问题,所以我猜你去了“手册”另外,将每个匹配项转换为一个整数,并将其乘以3。

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


如果其他用户遇到类似的问题,您能详细说明一下您是如何解决这个问题的吗?:)我不知道如何用Java来解决这个问题,但用Perl这很简单。:-P$foo='12 54 1 65';$foo=~s/(\d{1,2})/$1*3/eg;这里有一个答案描述了如何解决这个问题,我不知道它现在在哪里。。。(我接受了一个可以解决问题的问题,但消失了。奇怪…)我认为[这个问题][1]的答案可以帮助你。[1]:
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();
}
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));

  }
}