Gerber, Christopher J wrote, on Thursday, April 01, 2004 2:12 PM
:  -----Original Message-----
:  My guess is that I need a regex that will match on any character that is:
:       not 0-9 
:       or 
:       more than one "." 
:       or 
:       more than one "-" 
:       or if "-" is not the first character of the string
:  
:  Any ideas? Is it possible to do without using additional modules?
:  --------------------------
:  I haven't written a regex in a few months, but how about something like
:  this:
:  
:    for ("2.314","-2.314","7","-7","2.31.4","7-7","UNKNOWN","7+E09") {
:      $txtype=$_;
:      $txtype=0 unless /^-?((\d+)|(\d*\.\d+)|(\d+\.\d*))$/;
:      print "$_ => $txtype\n";
:    }
:  
:  ^            match beginning of string
:  -?           string MIGHT begin with a -
:  (\d+)                string of numbers with no .
:  (\d*\.\d+)   string of numbers with a . (digits only required AFTER .)
:  (\d+\.\d*)   string of numbers with a . (digits only required BEFORE .)
:  (..|..|..)   pick one of the three options for a match
:  $            match end of the string

I'd make just a few suggestions. First, since there's no need for capture,
dispense with the internal capturing parentheses, and make the outer ones
non-capturing. This will speed up the regex engine a little, and if there's
a lot of stuff to go through...

Secondly, if you make your decimal optional in the third alternation,
it's no different from the first, so you can eliminate one of the alternatives.
Then you've also matched those with *any* digits before the decimal, so you
can remove the leading \d* from the other alternative.

So I get:

/^-?(?:\d+\.?\d*|\.\d+)$/

for the regex. Just a slight improvement (and a shorter regex is almost
always more readable, too). You could embed the comments in the regex
(use the /x flag) to make it crystal clear.

Joe

==============================================================
          Joseph P. Discenza, Sr. Programmer/Analyst
               mailto:[EMAIL PROTECTED]
 
          Carleton Inc.   http://www.carletoninc.com
          574.243.6040 ext. 300    fax: 574.243.6060
 
Providing Financial Solutions and Compliance for over 30 Years
***** Please note that our Area Code has changed to 574! *****  




_______________________________________________
Perl-Win32-Users mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to