2017-04-07 117 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