ORO

Perl5Util は何故か気に食わないので、1.4のjava.util.regex に近いI/Fの使い方をば。

code

import java.util.*;
import org.apache.oro.text.regex.*;

public class Test
{
  public static void main(String[] args) throws Exception
  {
    Perl5Compiler compiler = new Perl5Compiler();
    Perl5Matcher matcher = new Perl5Matcher();
    
    // matches-1
    {
      Pattern pattern = compiler.compile("^(\\d+)\\.(\\d+)$");
      if( matcher.matches("234.455", pattern) )
      {
        MatchResult r = matcher.getMatch();
        for(int i=0, len=r.groups(); i<len; ++i)
        {
          System.out.println( "[matches-1][" + i + "]" + r.group(i) );
        }
      }
    }
    
    // matches-2
    {
      Pattern pattern = compiler.compile("(\\d+)-(\\d+)");
      PatternMatcherInput input = new PatternMatcherInput("aaa11-22.33-44bbb");
      while( matcher.contains(input, pattern) )
      {
        MatchResult r = matcher.getMatch();
        for(int i=0, len=r.groups(); i<len; ++i)
        {
          System.out.println( "[matches-2][" + i + "]" + r.group(i) );
        }
      }      
    }
    
    // split
    {
      Pattern pattern = compiler.compile("\\s*=\\s*");
      ArrayList c = new ArrayList();
      Util.split(c, matcher, pattern, "=aaa = bbb=ccc =", Util.SPLIT_ALL);
      System.out.println("[split-all]" + c );

      c.clear();
      Util.split(c, matcher, pattern, "=aaa = bbb=ccc =", 2);
      System.out.println("[split-count]" + c );
    }
    
    // replace
    {
      Pattern pattern = compiler.compile("\\d+");
      Perl5Substitution s = new Perl5Substitution("@");
      String r = Util.substitute(matcher, pattern, s, "aa11bb22cc", Util.SUBSTITUTE_ALL );
      System.out.println( "[replace-all]" + r );

      r = Util.substitute(matcher, pattern, s, "aa11bb22cc", 1 );
      System.out.println( "[replace-count]" + r );
    }
  }
}

result

[matches-1][0]234.455
[matches-1][1]234
[matches-1][2]455
[matches-2][0]11-22
[matches-2][1]11
[matches-2][2]22
[matches-2][0]33-44
[matches-2][1]33
[matches-2][2]44
[split-all][, aaa, bbb, ccc, ]
[split-count][, aaa = bbb=ccc =]
[replace-all]aa@bb@cc
[replace-count]aa@bb22cc