在GWT regexp中使用捕获组

时间:2012-02-15 19:25:58

标签: java regex gwt

我有一些使用Oracle正则表达式的代码,我想将其移植到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);
    }
}

我已尝试将其移植到GWT regexp库,但它通过start(int)方法使用捕获组,这在GWT regexp中似乎​​不受支持。

有没有办法模拟这种行为?

API参考:

Oracle regex

GWT regexp

1 个答案:

答案 0 :(得分:7)

来自GWT - 2.1 RegEx class to parse freetext

以下是如何在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);
}

(编辑:在Regexp.compile中添加“g”)

相关问题