[Tutor] Is it possible to load variable into a regex string?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Apr 27 23:14:00 CEST 2005

On Wed, 27 Apr 2005, Tom Tucker wrote:

> Hello all! I am trying to pass a variable to my re.compile string (see
> broken example below). Is something like this possible?  Thanks!
> regexstring = 'H\sb'
> textstring = 'BLAH blah'
> match = re.compile((%s) % (regexstring))  # ?

Hi Tom,

Ah, I think I see what you're trying to do.  I think you were trying to

    match = re.compile("%s" % (regexstring))

which uses string formatting to pull the 'regexstring' in, and then passes
the result off to re.compile().

But it might be better to just directly compile the regex string, without
the intermediate string formatting:

    match = re.compile(regexstring)

Does that make sense?

One other note: your regex string definition:

> regexstring = 'H\sb'

might need a slight adjustment, since you want to maintain that backslash
in the string literal.  Try:

    regexstring = r'H\sb'

The leading "r' in front of the string literal tells Python not to treat
internal backslashes as the escape character.  This "raw mode" is
especially useful for regular expressions, which use literal backslashes
heavily as metacharacters.

If you have more questions, please feel free to ask.  Good luck!

More information about the Tutor mailing list