0

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?

APIs references:

Oracle regex

GWT regexp

1

1 Answer 1

7

From GWT - 2.1 RegEx class to parse freetext :

Here's how you can iterate through them in GWT:

RegExp pattern = RegExp.compile(expression, "g");
for (MatchResult result = pattern.exec(source); result != null; result = pattern.exec(source)) 
{
    if (result.getGroup(1) != null && result.getGroup(1).length() > 0)
    {
        // it's an "abc" match
    }
    else if (result.getGroup(2) != null && result.getGroup(2).length() > 0)
    {
        // it's a "def" match
    }
    else
    {
        // should not happen
    }

    String substring = result.getGroup(0);
    System.out.println(substring);
}

(edit: added "g" in Regexp.compile)

2
  • Nice, I started to try to write this myself, but got bogged down in the differentce, rather than just continuing on. Feb 16, 2012 at 2:34
  • The example here will result in infinite loop. Finding the first and the same occurrence in every iteration. You need to pass "global flag" to the compile method. RegExp pattern = RegExp.compile(expression, "g");
    – TondaCZE
    Oct 2, 2014 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.