[Cialug] OT: can somebody help me with a regular expression?

Daniel A. Ramaley daniel.ramaley at DRAKE.EDU
Mon Jul 28 08:42:53 CDT 2008


On Friday July 25 2008 22:38, Chris Freeman wrote:
>I just realized there's a slight problem with this: '1,234567' will
> match, which isn't ideal. You'll have to decide if that's
> significant. If so, split it into two regexes, one with commas and
> one without. Otherwise, you could do this (not recommended due to
> obtuseness):
>
>(\s|^)(|D|PP)\d{1,3}(,(\d{1,3}(,\d{1,3})*)|(\d{1,3})*)(\s|$)

To me this is a *little* easier to read:

(?:\s|^)((?:|D|PP)\d{1,3}(?:(?:,\d\d\d)*|\d*))(?:\s|$)

After running that in Perl, $1 will contain the number that matched, $2 
and above will not have been defined. If you don't care about not 
capturing all the subparts you could pull out the "?:" sequences:

(\s|^)((|D|PP)\d{1,3}((,\d\d\d)*|\d*))(\s|$)

In that case i think $2 would hold the string that matched, but i didn't 
test it.

------------------------------------------------------------------------
Dan Ramaley                            Dial Center 118, Drake University
Network Programmer/Analyst             2407 Carpenter Ave
+1 515 271-4540                        Des Moines IA 50311 USA


More information about the Cialug mailing list