我正在尝试在GWT中使用RegExp和MatchResult。它仅返回单词中的首次出现。我需要同时具有三个“g”,“i”,“m”。我尝试了“gim”,它是全局,多行且不区分大小写的。但这是行不通的。请在下面找到代码。提前致谢。

预期的输出是,无论哪种情况,它都应在“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);
            }
        }
    }
  }
}

最佳答案

如果需要收集所有匹配项,请运行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(多行修饰符)仅影响模式中的^$,因此,您在这里不需要它。

07-24 09:47
查看更多