zzzbbx
zzzbbx

Reputation: 10131

Python regular expression with string in it

I would like to match a string with something like:

re.match(r'<some_match_symbols><my_match><some_other_match_symbols>', mystring)  

where mymatch is a string I would like it to find. The problem is that it may be different from time to time, and it is stored in a variable. Would it be possible to add one variable to a regex?

Upvotes: 1

Views: 128

Answers (3)

perreal
perreal

Reputation: 97938

import re
url = "www.dupe.com"
expression = re.compile('<p>%s</p>'%url)
result = expression.match("<p>www.dupe.com</p>BBB")
if result:
  print result.start(), result.end()

Upvotes: 0

poke
poke

Reputation: 387557

Nothing prevents you from simply doing this:

re.match('<some_match_symbols>' + '<my_match>' + '<some_other_match_symbols>', mystring)

Regular expressions are nothing else than a string containing some special characters, specific to the regular expression syntax. But they are still strings, so you can do whatever you are used to do with strings.

The r'…' syntax is btw. a raw string syntax which basically just prevents any escape sequences inside the string from being evaluated. So r'\n' will be the same as '\\n', a string containing a backslash and an n; while '\n' contain a line break.

Upvotes: 2

Michael Lorton
Michael Lorton

Reputation: 44376

The r'' notation is for constants. Use the re library to compile from variables.

Upvotes: -1

Related Questions