Matching multiple characters any times with Quantifiers - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Introduction

The quantifiers listed in the following table create patterns that match a variable number of characters in the string.

Regex Matches the Preceding Element. . .
? Zero or one times
* Zero or more times
+ One or more times
{n} Exactly n times
{n,}At least n times
{n,m} At least n times but no more than m times

To use a quantifier, add it immediately after the element you want it to apply to.

Here's a version of the Social Security number pattern that uses quantifiers:

The pattern matches three digits, followed by a hyphen, followed by two digits, followed by another hyphen, followed by four digits.

Demo Code

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

public class Main {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("\\d{3}-\\d{2}-\\d{4}");
    Matcher matcher = pattern.matcher("123-12-1212");
    if (matcher.matches())
      System.out.println("Match.");
    else//from  ww w .j av  a  2s  . c  o  m
      System.out.println("Does not match.");
  }

}

Related Tutorials