2012-02-15 47 views
0

我有一些使用Oracle正則表達式的代碼,我想將它們移植到GWT。在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的正則表達式庫,但它會通過啓動(int)方法,這似乎並沒有在GWT正則表達式得到支持捕獲組。

有沒有辦法模擬這種行爲?

的API參考:

Oracle regex

GWT regexp

+0

請看一下:http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/regexp/ shared/RegExp.html你錯過了什麼? – 2012-02-16 00:30:20

回答

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」)

+0

不錯,我開始嘗試自己寫這個,但陷入了不同的局面,而不是繼續。 – 2012-02-16 02:34:47

+0

這裏的例子將導致無限循環。在每次迭代中查找第一個和相同的事件。您需要將「全局標誌」傳遞給編譯方法。 RegExp pattern = RegExp.compile(expression,「g」); – TondaCZE 2014-10-02 14:37:52

+0

好,我已經更新了我的回覆。 – 2014-11-06 22:01:10