Greedy and Nongreedy Matching in a Regular Expression : Greedy « Regular Expressions « Java






Greedy and Nongreedy Matching in a Regular Expression


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] argv) throws Exception {
    // Greedy quantifiers
    String match = find("A.*c", "AbcAbc"); 
    match = find("A.+", "AbcAbc"); 

  }

  public static String find(String patternStr, CharSequence input) {
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(input);
    if (matcher.find()) {
      return matcher.group();
    }
    return null;
  }
}

 








Related examples in the same category

1.Greedy Qualifier
2.Reluctant Qualifier Example
3.Nongreedy quantifiers