Recipes
Removing leading and trailing whitespace
s/^\s+// s/\s+$//
Matches: " foo bar
â, "foo
"
Nonmatches: "foo bar"
Numbers from 0 to 999999
/^\d{1,6}$/
Matches: 42
, 678234
Nonmatches: 10,000
Valid HTML Hex code
/^#([a-fA-F0-9]){3}(([a-fA-F0-9]){3})?$/
Matches: #fff
, #1a1
, #996633
Nonmatches: #ff
, FFFFFF
U.S. Social Security number
/^\d{3}-\d{2}-\d{4}$/
Matches: 078-05-1120
Nonmatches: 078051120
, 1234-12-12
U.S. zip code
/^\d{5}(-\d{4})?$/
Matches: 94941-3232
, 10024
Nonmatches: 949413232
U.S. currency
/^\$\(d{1,3}(\,\d{3})*|\d+)(\.\d{2})?$/
Matches: $20
, $15,000.01
Nonmatches: $1.001
, $.99
Match date: MM/DD/YYYY HH:MM:SS
/^\d\d\/\d\d\/\d\d\d\d \d\d:\d\d:\d\d$/
Matches: 04/30/1978 20:45:38
Nonmatches: 4/30/1978 20:45:38
, 4/30/78
Leading pathname
/^.*\//
Matches: /usr/local/bin/apachectl
Nonmatches: C:\\System\foo.exe
(See MRE 190â192.)
Dotted Quad IP address
/^(\d|[01]?\d\d|2[0-4]\d|25[0-5])\.(\d|[01]?\d\d|2[0-4]\d|25[0-5])\. (\d|[01]?\d\d|2[0-4]\d|25[0-5])\.(\d|[01]?\d\d|2[0-4]\d|25[0-5])$/
Matches: 127.0.0.1
, 224.22.5.110
Nonmatches: 127.1
(See MRE 187â189.)
MAC address
/^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$/
Matches: 01:23:45:67:89:ab
Nonmatches: 01:23:45
, 0123456789ab
/^[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-\w]* [0-9a-zA-Z]\.)+[a-zA-Z]{2,9}$/
Matches: tony@example.com, tony@i-e.com, tony@mail.example.museum
Nonmatches: .@example.com, tony@i-.com, tony@example.a
(See MRE 70.)
HTTP URL
/(https?):\/\/([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9}) (:\d{1,4})?([-\w\/#~:.?+=&%@~]*)/
Matches: https://example.com ...
Get Regular Expression Pocket Reference, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.