Skip to content

appendReplacement doesn't throw for invalid replacement groups #196

Description

@cushon

appendReplacement doesn't throw an exception for invalid replacement groups, which is inconsistent with java.util.regex. Is this deliberate, or should the behaviour match java.util.regex?

    String pattern = "(.*)";
    String input = "hello";
    {
      System.err.println("> re2j");
      var p = com.google.re2j.Pattern.compile(pattern);
      var m = p.matcher(input);
      StringBuilder sb = new StringBuilder();
      while (m.find()) {
        m.appendReplacement(sb, "$foo");
      }
      System.err.println(sb);
    }
    {
      System.err.println("> java.util.regex");
      var p = java.util.regex.Pattern.compile(pattern);
      var m = p.matcher(input);
      StringBuilder sb = new StringBuilder();
      while (m.find()) {
        m.appendReplacement(sb, "$foo");
      }
      System.err.println(sb);
    }
> re2j
$foo$foo

> java.util.regex
java.lang.IllegalArgumentException: Illegal group reference
	at java.base/java.util.regex.Matcher.appendExpandedReplacement(Matcher.java:1111)
	at java.base/java.util.regex.Matcher.appendReplacement(Matcher.java:1041)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions