RegExp and MatchResult in GWT only return the first match

I am trying to use RegExp and MatchResult in GWT. It only returns the first occurrence of the word. I need to have all three "g", "i", "m". I've tried "gim", which is global, multi-line and case insensitive. But it doesn't work. Please find the code below. Thanks in advance.

Expected Result: It should find 3 matches "on" in "On Condition" regardless of case.

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

      

+3


source to share


1 answer


If you need to collect all the matches, run exec

until you get a match.

To replace multiple occurrences of a search term, use RegExp#replace()

with a pattern enclosed in a capture group (I was unable to make a backlink $&

for all match work in GWT).

Change the code as follows:



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
}

      

Note that the m

(multi-line modifier) โ€‹โ€‹only affects ^

and $

in the template, so you don't need to here.

+3


source







All Articles