Quantifier

In this chapter you will learn:

  1. What are quantifiers in regular expressions
  2. How to use + quantifier

Quantifiers

A quantifier determines how many times an expression is matched.

The quantifiers are shown here:

SymbolMeaning
+Match one or more.
*Match zero or more.
?Match zero or one.

For example, the pattern "x+" will match "x", "xx", and "xxx".

Use + quantifier

The following example that uses the + quantifier to match any arbitrarily long sequence of As.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
//from  jav  a2 s . c o m
public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("A+");
    Matcher mat = pat.matcher("A AA AAA");
    while (mat.find()){
      System.out.println("Match: " + mat.group());
    }      
  }
}

The code above generates the following result.

The code above creates a pattern A+. + is a quantifier matching one or more. A+ means to match one A or more As, more As can be AA, AAA or AAAA...

Next chapter...

What you will learn in the next chapter:

  1. How to match words start and end
Home » Java Tutorial » Regular Expressions
Regular Expression Processing
Normal characters
Character class
Wildcard Character
Quantifier
Wildcards and Quantifiers
Character class and quantifiers
Find sub string
Multiple subsequences
Replace all
Split