Regular Expression Exercise S1
The first in a series of exercises designed to teach you more about regular expressions, written by a guy who got partway through writing a regex book.
But first, a word about tools. It's a lot easier to use a tool to do this sort of thing than it is to write code to do it. So, I suggest one of the following:
- The Regulator. No fair to use the library if you choose this tool. Uses a bit of code I wrote to analyze regex for you.
- Regular Expression Workbench (classic) . I wrote this
- Regular Expression Workbench (updated). Version with a different UI on it.
So, S stands for simple, 1 stands for 1, so this first one is going to be pretty simple.
S1 - Match a Social Security Number
Verify that a string is a social security number of the format ddd-dd-dddd.
Answer and explanation to follow.
Comments
Anonymous
October 21, 2005
^d{3}-d{2}-d{4}$Anonymous
October 21, 2005
Surely you'd want the hypens to be optional or replaceable by spaces. Forcing a particlular format when enter a number like this, or a credit-card number can be a pain, unless you explictly tell the user in advance the format you want (as you have done).
In any case, I'd use
^d{3}[-| ]?d{2}[-| ]?d{4}$Anonymous
October 23, 2005
The best tool one can have when working with regular expressions is Regex Coach. http://weitz.de/regex-coach/Anonymous
October 24, 2005
Dvae:
Yes, but you'd want consistency in the separator use, so that it would accept "123-12-1234", "123 12 1234" or "123121234" but not "12312 1234" or "123-12 1234". Hence we'd need:
^d{3}(?<Sep>[- ]?)d{2}<Sep>d{4}$
(as interpreted by Regex Workbench)
^ (anchor to start of string)
Any digit
Exactly 3 times
Capture to <Sep>
Any character in "- "
? (zero or one time)
End Capture
Any digit
Exactly 2 times
<Sep>
Any digit
Exactly 4 times
$ (anchor to end of string)Anonymous
October 24, 2005
> Yes, but you'd want consistency in the separator use
True, but if we wanted consistency, then we'd force them to use the properly structured format, and not allow for any variance ;-)
<strike>Dvae</strike> DaveAnonymous
October 27, 2005
Why would I want to match one of those? Completely useless outside the US.Anonymous
October 28, 2005
The comment has been removedAnonymous
November 06, 2005
The comment has been removedAnonymous
May 31, 2009
PingBack from http://woodtvstand.info/story.php?id=2664Anonymous
June 07, 2009
PingBack from http://greenteafatburner.info/story.php?id=2272Anonymous
June 17, 2009
PingBack from http://pooltoysite.info/story.php?id=3255