By Alvin Alexander. Last updated: June 4, 2016
Java FAQ: Can you share some examples of common Java regular expressions?
The following list shows some of the most common regular expressions that are used in computer programming. I haven’t tested any of these yet with Java, but I think most will work off the shelf, or should at least work with minor tweaks.
An interesting note is that there are several ways to write the same regular expression, and I intentionally tried to stress that in the examples below.
Regular Expression | What it Matches |
---|---|
^$ |
A blank line. |
[A-Z][A-Z] |
Two character state abbreviation. Note that you may choose to put spaces either before or after the regex. |
.*, [A-Z][A-Z] |
City, State abbreviation. |
[0-9]\{5\}(-[0-9]\{4\})? |
Zip Code. Five digits, followed by an optional hyphen and four additional digits. |
[0-9]\{3\}-[0-9]\{2\}-[0-9]\{4\} |
Social security number, such as:###-##-#### |
\$[0-9]*.[0-9][0-9] |
Dollar amounts, specified with a leading $ symbol. |
[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\} |
Date, in numeric format, such as 2003-08-06. |
[A-Z][a-z][a-z] [0-9][0-9]*, [0-9]\{4\} |
Date, in format such as "Jan 3, 2003 " |
I'll add more regular expressions as I think of them, but these are some of the first that come to mind. Hopefully many other common regular expressions can easily be extrapolated from these.