[oak perl] Regular Expressions
Tony Stubblebine
tonys at oreillynet.com
Wed Mar 10 14:55:36 CST 2004
Thanks George.
I'm curious to see what sort of regular expressions people are writing,
good and bad. And I'd love to start a discussion on regex style or
technique.
Here's my crazy phone number regex, which I thought was fun to write but
in hindsight probably not all that useful. It's got nested if-then-else
constructs, that was the fun part.
#!/usr/bin/perl
my @tests = ( #These match
"314-555-4000",
"800-555-4400",
"(314)555-4000",
"314.555.4000",
"1 800-555-4000",
"1-800-555-4000",
#These Fail
"1 800 555 5555",
"(800) 555 5555",
"800 555 5555",
"8005554444",
"1888-555-5555",
"1-800.555.4000",
"1-800-555.4000",
"1 800 555-4444",
"1-800 555-4000",
"800.555-4000",
"555-4000",
"aasdklfjklas",
"1234-123-12345",
"(800-555-1212",
"800)555-1212",
"800)-555-1212",
"800555-1212",
);
foreach my $test (@tests) {
if ( $test =~ m/
^
(?:
(?:
1 (?: \s | ([-.]) ) # 1 followed by optional separator
\d\d\d # followed by area code
( (?(1) \1 | [-.] ) ) # followed by separator
)
| # ... or ...
(?: \(\d\d\d\) \s? ) # area code with parens
| # ... or ...
(?: \d\d\d ([-.]) ) # area code with separator
)
\d\d\d # prefix
(?(2) # match separator from "1 followed by..."
\2 # clause
|
(?(3) \3 | [-.] ) # or match separator from "area code with
) # separator" clause
\d\d\d\d # exchange
$
/x ) {
print "Matched on $test [ $1 : $2 : $3 ]\n";
}
else {
print "Failed match on $test\n";
}
}
George Woolley wrote:
>Tony,
>Welcome to our mailing list.
>Thanks for your excellent talk last night!
>And thanks for joining the mailing list as a guest!
>George
>
>
>All,
>Here's the arrangement as I understand it.
>If you show some regex code you have written
>and request so,
>Tony will comment on it.
>
>He'll be around for a month,
>but may sometimes take a while to respond.
>Note that the deal is that you provide some regex code
>in your request.
>George
>
>
>Tony,
>Please feel free to correct or reframe anything above
>that is amiss.
>Also, very possibly, you have things to add.
>
>Enjoy!
>George
>
>==========================
>Oakland subscription notification
>Date: Today 11:37:18 am
>From: mailman-bounces at mail.pm.org
>To: oakland-owner at mail.pm.org
>
>Tony Stubblebine <tonys at oreilly.com> has been successfully subscribed
>to Oakland.
>
>_______________________________________________
>Oakland mailing list
>Oakland at mail.pm.org
>http://mail.pm.org/mailman/listinfo/oakland
>
>
More information about the Oakland
mailing list