Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-840

Provide a replaceAll() method on String to transform captured text through a closure

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Major
    • Resolution: Fixed
    • None
    • 1.0-JSR-2
    • None
    • None

    Description

      Transform each captured group into something else:

      assert "2 4 6 8" == "1 2 3 4".replaceAll("
      p

      {Digit}

      ")

      { it * 2 }

      With a new Groovy method on String:

      public static String replaceAll(String self, String regex, Closure
      closure) {
      Matcher matcher = Pattern.compile(regex).matcher(self);
      if (matcher.find()) {
      matcher.reset();
      StringBuffer sb = new StringBuffer();
      while (matcher.find())

      { String foundText = self.substring(matcher.start(0), matcher.end(0)); matcher.appendReplacement(sb, String.valueOf(closure.call( foundText ))); }

      matcher.appendTail(sb);
      return sb.toString();
      } else

      { return self; }

      }

      Attachments

        Activity

          People

            guillaume Guillaume Sauthier
            guillaume Guillaume Sauthier
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: