Java Regular Expression quantifier

Introduction

The asterisk * and + are called quantifiers.

The following table lists all the quantifiers.

QuantifierMatches
*Matches zero or more occurrences of the pattern.
+ Matches one or more occurrences of the pattern.
?Matches zero or one occurrences of the pattern.
{n} Matches exactly n occurrences.
{n ,}Matches at least n occurrences.
{n ,m} Matches between n and m (inclusive) occurrences.
public class Main {
  // execute application
  public static void main(String[] args) {
    String s = "12345";

    boolean b = s.matches("\\d{5}");
   //from   w  w  w  .  ja va 2 s.  c o m
    System.out.println(b);

  }
}

The following example uses the + quantifier to match any arbitrarily long sequence of Ws:

// Use a quantifier. 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("W+");
    Matcher mat = pat.matcher("W WW WWW");

    while (mat.find())
      System.out.println("Match: " + mat.group());
  }//from  w  w w .  j a v a 2s. c o  m
}



PreviousNext

Related