GWT returns 中的 RegExp 和 MatchResult 仅首次匹配

RegExp and MatchResult in GWT returns only first match

我正在尝试在 GWT 中使用 RegExp 和 MatchResult。它returns只在一个词中第一次出现。我需要所有三个 "g"、"i"、"m"。我尝试了 "gim" ,它是全局的、多行的和不区分大小写的。但它不起作用。请在下面找到代码。提前致谢。

预期的输出是,无论大小写如何,它都应该在 "On Condition" 中找到 "on" 的 3 个匹配项。

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);
            }
        }
    }
  }
}

如果您需要收集所有匹配项,运行 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");
    System.out.println(newDtoData);
    // => 1On0 C1on0diti1on0
}

请注意,m(多行修饰符)仅影响模式中的 ^$,因此此处不需要它。