Error checking using regex ?

Guy Robinson guy at NOSPAM.r-e-d.co.nz
Tue Jun 8 13:26:48 CEST 2004


I have the code below which parses an expression string and creates tokens.

Can anyone suggest the best of error checking for things like:

Valid variable only obj.attribute -whitespace allowed

test( "ff*2/dd.r..ss r")    #additional ..ss -invalid variable.
test( "ff*$24..55/ddr")     #double .. and $ -invalid number
test( "ff*2/dd.r.ss r")     #variable with double . -invalid variable

I can't see an efficient way of doing this so any suggestions appreciated.

TIA,

Guy

code:

import re
import time

re_par = '[\(\)]'
re_num = '[0-9]*\.?[0-9]+\E?[0-9]*'
re_opr = '[\*\/\+\-\^]'
re_cns = 'PI'
re_trg = 'SIN|COS|TAN|ASIN|ACOS|ATAN|SGN'
re_var = '[a-z_0-9\s]*\.?[a-z_0-9\s]*'

recom = re.compile( '(?P<token>%s|%s|%s|%s|%s|%s)' 
%(re_par,re_num,re_opr,re_cns,re_trg,re_var) ,re.VERBOSE|re.IGNORECASE)

def test(str):
     output = []
     try:
         r = recom.split(str)
         for rr in r:
             rr = rr.strip()
             #test for blank string
             if rr =='':
                 pass
             else:
                 output.append(rr)
         print output

     except:
         print 'error of some kind'

class stopwatch:

     def __init__(self):

         pass
     def start(self):

         self.t = time.time()
         return 'starting timer'

     def stop(self):

         rstr = 'stopped at %f seconds' %(time.time() -self.t)
         self.t = 0
         return rstr

e = stopwatch()
print e.start()
test( "9" )
test( "9 + 3 + 6" )
test( "9 + 3 / 11" )
test( "( 9 + 3)" )
test( "(9+3) / 11" )
test( "9 - 12 - 6" )
test( "-9 - (12 - 6)" )
test( "2*3.14159" )
test( "3.1415926535*3.1415926535 / 10" )
test( "PI * PI / 10" )
test( "PI*PI/10" )
test( "PI^2" )
test( "6.02E23 * 8.048" )
test( "sin(PI/2)" )
test( "2^3^2" )
test( "2^9" )
test( "sgn(-2)" )
test( "sgn(0)" )
test( "sgn(0.1)" )
test( "ff*2" )
test( "ff*g g/2" )
test( "ff*2/dd.r r")
test( "5*4+300/(5-2)*(6+4)+4" )
test( "((5*4+300)/(5-2))*(6+4)+4" )
test( "(320/3)*10+4" )

#now test error expressions

test( "ff*2/dd.r..ss r")    #additional ..ss and whitespace -invalid 
variable
test( "ff*$24..55/ddr")     #double .. -invalid number
test( "ff*2/dd.r.ss r")     #variable with double . -invalid variable
#test( "ff*((w.w+3)-2")      #no closing parentheses-to be tested when 
evaluating expression

print e.stop()



More information about the Python-list mailing list