regular expression question

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Feb 14 20:38:43 EST 2005


snacktime a écrit :
> The primary question is how do I perform a match when the regular
> expression contains string variables?  For example, in the following
> code I want to match a line that starts with STX, then has any number
> of characters, then ends with STX.
> Example 2 I'm pretty sure works as I expect, but I'm not sure about
> Example 1, and I'm pretty sure about example 3.
> 
> import re
> from curses.ascii import STX,ETX,FS
> STX =  chr(STX)
> ETX =  chr(ETX)
> FS =  chr(FS)
> data = STX + "ONE" + FS + "TWO" + FS + "THREE" + ETX
> match = STX + '(.*)' + ETX
> 
> # Example 1
> # This appears to work, but I'm not sure if the '+' is being used in
> the regular expression, or if it's just joining STX, '(.*)', and ETX.
> 
> if re.search(STX + '(.*)' + ETX,data):
>   print "Matches"
> 
> # Example 2
> # This also appears to work
> if re.search(match,data):
>   print "Matches"
> 
> # Example 3
> # Doesn't work, as STX and ETX are evaluated as the literal strings
> 'STX' and 'ETX'
> if re.search('STX(.*)ETX', data):
>   print "Matches"

You may want something like:
if re.search('%s(.*)%s' % (STX, ETX), data):
   ...

BTW, given your requirements, I'd write this:
if re.search('^%s(.*)%s$' % (STX, ETX), data):
   ...



> Chris



More information about the Python-list mailing list