Using capturing groups in GWT regexp

124 views
Skip to first unread message

Dominic Hudon

unread,
Feb 15, 2012, 2:43:48 PM2/15/12
to google-we...@googlegroups.com
I have some code using Oracle regex that I want to port to GWT.

public static void main( String[] args )
{
    String expression = "(abc)|(def)";
    String source = "abcdef";
    
    Pattern pattern = Pattern.compile(expression);
    Matcher matcher = pattern.matcher(source);
    
    while (matcher.find())
    {
        if (matcher.start(1) != -1)
        {
            // it's an "abc" match
        }
        else if (matcher.start(2) != -1)
        {
            // it's a "def" match
        }
        else
        {
            // error
            continue;
        }
        
        int start = matcher.start();
        int end = matcher.end();
        
        String substring = source.substring(start, end);
        System.out.println(substring);
    }
}

I’ve tried porting it to the GWT regexp library, but it uses capturing groups through the start(int) method, which doesn’t seem to be supported in GWT regexp.

Is there a way to simulate this behaviour?

Joseph Lust

unread,
Feb 17, 2012, 12:34:47 PM2/17/12
to Google Web Toolkit
Use the GWT RegExp class. The following gets all the matching strings:

// does what I think you were looking for
String pattern = "(abc)|(def)";
String input = "abczdefzabc";

RegExp regExp = RegExp.compile(pattern, "g");
MatchResult matcher = regExp.exec(input);

// could probably use a doWhile to make it simpler
while(matcher!=null) {
System.out.println( "Found match str: "
+matcher.getGroup(0) );
matcher = regExp.exec(input);
}


Sincerely,
Joe


On Feb 15, 2:43 pm, Dominic Hudon <dominic.hu...@gmail.com> wrote:
> I have some code using Oracle regex that I want to port to GWT.
>
> public static void main( String[] args )
> {
>     String expression = "(abc)|(def)";
>     String source = "abcdef";
>
>     Pattern pattern = Pattern.compile(expression);
>     Matcher matcher = pattern.matcher(source);
>
>     while (matcher.find())
>     {
>         if (matcher.start(1) != -1)
>         {
>             // it's an "abc" match
>         }
>         else if (matcher.start(2) != -1)
>         {
>             // it's a "def" match
>         }
>         else
>         {
>             // error
>             continue;
>         }
>
>         int start = matcher.start();
>         int end = matcher.end();
>
>         String substring = source.substring(start, end);
>         System.out.println(substring);
>     }
>
> }
>
> I’ve tried porting it to the GWT regexp library, but it uses capturing
> groups through the start(int) method, which doesn’t seem to be supported in
> GWT regexp.
>
> Is there a way to simulate this behaviour?
>
> Oracle regex:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/package-...
>
> GWT regexp:http://google-web-toolkit.googlecode.com/svn/javadoc/2.1/com/google/g...
Reply all
Reply to author
Forward
0 new messages