我想在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);
}
}
}
}
}
嘗試解決這種方式:'字符串newDtoData = DtoValue;' 和 'MatchResult的匹配= regExp.exec(dtoValue); (matcher!= null){newDtoData = newDtoData.replaceFirst(RegExp.quote(matcher.getGroup()),「」+ i); System.out.println(newDtoData); matcher = regExp.exec(dtoValue); }' –
這工作!謝謝@WiktorStribiżew – Kutty