Python 2.6+ Str.format() And Regular Expressions
Using str.format() is the new standard for formatting strings in Python 2.6, and Python 3. I've run into an issue when using str.format() with regular expressions. I've written a r
Solution 1:
you first would need to format string and then use regex. It really doesn't worth it to put everything into a single line. Escaping is done by doubling the curly braces:
>>> pat= '^(w{{3}}\.)?([0-9A-Za-z-]+\.){{1}}{domainName}$'.format(domainName = 'delivery.com')
>>> pat
'^(w{3}\\.)?([0-9A-Za-z-]+\\.){1}delivery.com$'
>>> re.match(pat, str1)
Also, re.match
is matching at the beginning of the string, you don't have to put ^
if you use re.match
, you need ^
if you're using re.search
, however.
Please note, that {1}
in regex is rather redundant.
Solution 2:
Per the documentation, if you need a literal {
or }
to survive the formatting opertation, use {{
and }}
in the original string.
'^(w{{3}}\.)?([0-9A-Za-z-]+\.){{1}}{domainName}$'.format(domainName = 'delivery.com')
Post a Comment for "Python 2.6+ Str.format() And Regular Expressions"