Greedy and Nongreedy Matching in a Regular Expression - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Description

Greedy and Nongreedy Matching in a Regular Expression

Demo Code



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

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

    // Nongreedy quantifiers
    match = find("A.*?c", "AbcAbc"); // Abc
    match = find("A.+?", "AbcAbc"); // Abc
  }/*from   w w w. j  a v a 2  s  .c om*/
  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 Tutorials