Nongreedy quantifiers : Greedy « Regular Expressions « Java






Nongreedy quantifiers


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

public class Main {
  public static void main(String[] argv) throws Exception {
    // Nongreedy 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 and Nongreedy Matching in a Regular Expression
2.Greedy Qualifier
3.Reluctant Qualifier Example