在Python 2.6和Python 3中,使用str.format()
是格式化字符串的新标准。但是当我在使用str.format()
与正则表达式一起时遇到了问题。
我编写了一个正则表达式来返回所有在指定域名下面一级的域名,或者是第二级域名为www且在指定域名下面两级的域名...
假设指定的域名为delivery.com,那么我的正则表达式应该返回a.delivery.com、b.delivery.com、www.c.delivery.com...但不应返回x.a.delivery.com。
import re
str1 = "www.pizza.delivery.com"
str2 = "w.pizza.delivery.com"
str3 = "pizza.delivery.com"
if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str1): print 'String 1 matches!'
if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str2): print 'String 2 matches!'
if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str3): print 'String 3 matches!'
运行此命令应该会得到以下结果:
String 1 matches!
String 3 matches!
现在的问题是,当我尝试使用str.format动态替换delivery.com时...
if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}{domainName}$'.format(domainName = 'delivery.com'), str1): print 'String 1 matches!'
这似乎会失败,因为
str.format()
期望{3}
和{1}
是函数的参数。(我假设)
我可以使用+运算符连接字符串。
'^(w{3}\.)?([0-9A-Za-z-]+\.){1}' + domainName + '$'
问题归结为:当字符串(通常是正则表达式)中包含“{n}”时,是否可以使用
str.format()
?