Java Regular Expression wildcard greedy behavior

Introduction

The following code uses a wildcard to create a pattern.

It will match any sequence that begins with e and ends with d.

To do this, it uses the dot wildcard character along with the + quantifier.


// Use wild card and quantifier. 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("e.+d");
    Matcher mat = pat.matcher("extend cup end table");

    while (mat.find())
      System.out.println("Match: " + mat.group());
  }/* w  ww  . j a  v  a2 s .co m*/
}

Only one match is found, and it is the longest sequence that begins with e and ends with d.

The longer sequence is found by default by find().

By default find() matches the longest sequence that fits the pattern.

This is called greedy behavior.




PreviousNext

Related