Java examples for Regular Expressions:Pattern
Suppose you want to allow the user to enter Social Security numbers without the hyphens.
The question marks indicate that the hyphens are optional.
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."); } }