2017-04-07 112 views
3

我想在GWT中使用RegExp和MatchResult。它只返回一個單詞中的第一個匹配項。我需要所有的三個「克」,「我」,「米」。我嘗試了全球化,多行和不區分大小寫的「gim」。但它不起作用。請找到下面的代碼。提前致謝。GWT中的RegExp和MatchResult只返回第一個匹配

預期的輸出是,它應該在「On Condition」中找到3個匹配的「on」,與情況無關。

import com.google.gwt.regexp.shared.MatchResult; 
import com.google.gwt.regexp.shared.RegExp; 

public class PatternMatchingInGxt { 

public static final String dtoValue = "On Condition"; 
public static final String searchTerm = "on"; 

public static void main(String args[]){ 
    String newDtoData = null; 
    RegExp regExp = RegExp.compile(searchTerm, "mgi"); 
    if(dtoValue != null){ 
     MatchResult matcher = regExp.exec(dtoValue); 
     boolean matchFound = matcher != null; 
     if (matchFound) { 
      for (int i = 0; i < matcher.getGroupCount(); i++) { 
       String groupStr = matcher.getGroup(i); 
       newDtoData = matcher.getInput().replaceAll(groupStr, ""+i); 
       System.out.println(newDtoData); 
      } 
     } 
    } 
    } 
} 
+1

嘗試解決這種方式:'字符串newDtoData = DtoValue;' 和 'MatchResult的匹配= regExp.exec(dtoValue); (matcher!= null){newDtoData = newDtoData.replaceFirst(RegExp.quote(matcher.getGroup()),「」+ i); System.out.println(newDtoData); matcher = regExp.exec(dtoValue); }' –

+0

這工作!謝謝@WiktorStribiżew – Kutty

回答

3

如果您需要收集所有匹配項,請運行exec,直到找不到匹配項爲止。

要更換搜索詞的多次出現,使用RegExp#replace()與包裹着捕獲組(我不能讓$&反向引用在GWT全場比賽工作)模式

更改如下代碼:

if(dtoValue != null){ 

    // Display all matches 
    RegExp regExp = RegExp.compile(searchTerm, "gi"); 
    MatchResult matcher = regExp.exec(dtoValue); 
    while (matcher != null) { 
     System.out.println(matcher.getGroup(0)); // print Match value (demo) 
     matcher = regExp.exec(dtoValue); 
    } 

    // Wrap all searchTerm occurrences with 1 and 0 
    RegExp regExp1 = RegExp.compile("(" + searchTerm + ")", "gi"); 
    newDtoData = regExp1.replace(dtoValue, "1$10"); 
    System.out.println(newDtoData); 
    // => 1On0 C1on0diti1on0 
} 

注意m(多修飾符)僅在模式影響^$,因此,你不需要在這裏。

+0

匹配器沒有getGroup()。所以,我添加了一個for循環,並將代碼修改爲matcher.getGroup(i) – Kutty

+1

然後,您只需通過將0傳遞給它即可訪問組0。由於該模式沒有捕獲組,因此不需要任何循環,即匹配數據對象只有一個單獨的組。請檢查'matcher.getGroup(0)'。 –

+0

你是唯一!我按照你的說法修改。非常感謝:) – Kutty