Kutty
Kutty

Reputation: 722

RegExp and MatchResult in GWT returns only first match

I am trying to use RegExp and MatchResult in GWT. It returns only first occurrence in a word. I need to have all the three "g", "i", "m". I tried "gim" which is global, multiline and case insensitive. But it is not working. Please find the code below. Thanks in advance.

The expected output is, it should find 3 matches of "on" in "On Condition" irrespective of the 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);
            }
        }
    }
  }
}

Upvotes: 3

Views: 776

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627022

If you need to collect all matches, run exec until you get no match.

To replace multiple occurrences of the search term, use RegExp#replace() with a pattern wrapped with a capturing group (I could not make $& backreference to the whole 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 m (multiline modifier) only affects ^ and $ in the pattern, thus, you do not need it here.

Upvotes: 3

Related Questions