? quantifier create an optional element that may or may not be present in the string - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Introduction

Suppose you want to allow the user to enter Social Security numbers without the hyphens.

The question marks indicate that the hyphens are optional.

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("779121212");
    if (matcher.matches())
      System.out.println("Match.");
    else//from www  .  ja va  2  s.co  m
      System.out.println("Does not match.");
  }

}

Related Tutorials