代码之家  ›  专栏  ›  技术社区  ›  user

JavaReX替换为捕获组

  •  67
  • user  · 技术社区  · 15 年前

    是否有任何方法可以用捕获组的修改内容替换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();
    }
    

    它引发非法状态异常:未找到匹配项

    但是

    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();
    }
    

    很好,但是我不能换1美元:(

    编辑:

    现在,它开始工作了:)

    3 回复  |  直到 8 年前
        1
  •  74
  •   earl    15 年前

    怎么样:

    if (regexMatcher.find()) {
        resultString = regexMatcher.replaceAll(
                String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
    }
    

    要获得第一场比赛,请使用 #find() .之后,您可以使用 #group(1) 参考第一个匹配,并用第一个maches值乘以3替换所有匹配。

    如果要用该匹配项的值乘以3替换每个匹配项:

        Pattern p = Pattern.compile("(\\d{1,2})");
        Matcher m = p.matcher("12 54 1 65");
        StringBuffer s = new StringBuffer();
        while (m.find())
            m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
        System.out.println(s.toString());
    

    你可能想看看 Matcher 's documentation 详细介绍了这一点和更多内容。

        2
  •  11
  •   Draemon    15 年前

    厄尔的回答给了你解决方案,但我想我要补充一下是什么问题导致了你 IllegalStateException . 你在打电话 group(1) 没有首先调用匹配操作(例如 find() )如果你只是在使用 $1 自从 replaceAll() 是匹配的操作。

        3
  •  1
  •   Mike    8 年前

    来源: java-implementation-of-rubys-gsub

    用途:

    // Rewrite an ancient unit of length in SI units.
    String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
        public String replacement() {
            float inches = Float.parseFloat(group(1));
            return Float.toString(2.54f * inches) + " cm";
        }
    }.rewrite("a 17 inch display");
    System.out.println(result);
    
    // The "Searching and Replacing with Non-Constant Values Using a
    // Regular Expression" example from the Java Almanac.
    result = new Rewriter("([a-zA-Z]+[0-9]+)") {
        public String replacement() {
            return group(1).toUpperCase();
        }
    }.rewrite("ab12 cd efg34");
    System.out.println(result);
    

    实施(重新设计):

    import static java.lang.String.format;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public abstract class Rewriter {
        private Pattern pattern;
        private Matcher matcher;
    
        public Rewriter(String regularExpression) {
            this.pattern = Pattern.compile(regularExpression);
        }
    
        public String group(int i) {
            return matcher.group(i);
        }
    
        public abstract String replacement() throws Exception;
    
        public String rewrite(CharSequence original) {
            return rewrite(original, new StringBuffer(original.length())).toString();
        }
    
        public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
            try {
                this.matcher = pattern.matcher(original);
                while (matcher.find()) {
                    matcher.appendReplacement(destination, "");
                    destination.append(replacement());
                }
                matcher.appendTail(destination);
                return destination;
            } catch (Exception e) {
                throw new RuntimeException("Cannot rewrite " + toString(), e);
            }
        }
    
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(pattern.pattern());
            for (int i = 0; i <= matcher.groupCount(); i++)
                sb.append(format("\n\t(%s) - %s", i, group(i)));
            return sb.toString();
        }
    }