A social security number (123-45-6789) can be found using the regular expression:
^[0-9]{3}-{1}[0-9]{2}-{1}[0-9]{4}$
If no quantifier is given, then one match is required.
In the example above, if the social security may or may not have hyphens, alter the expressions to match the new syntax. Use the regular expression below:
^[0-9]{3}-?[0-9]{2}-?[0-9]{4}$
The regular expression can be shortened as well using metacharacters:
^\d{3}-?\d{2}-?\d{4}$
To match a Customer PO Number that is comprised of two alpha numeric characters, followed by five digits, followed by a “P”, “S” or “D”, when each of the three components has an optional hyphen between them:
[0-9A-Z] Matches a digit or letter, so [0-9A-Z]{2} would match exactly 2 digits or letters.
When a question mark follows an item, it means that either zero or one of the preceding things occur, so [0-9A-Z]{2}-? matches exactly two digits or letters with or without a trailing hyphen:
[0-9A-Z]{2}-?[0-9]{5}-?[PSD]
Two anchors are needed ( ^ and $ ) to indicate this must appear at both the beginning and the end of the string (and therefore be equal to the string). The slashes denote that a regular expression is being entered:
^[0-9A-Z]{2}-?[0-9]{5}-?[PSD]$