【发布时间】:2010-12-24 22:39:15
【问题描述】:
使用str.format() 是在Python 2.6 和Python 3 中格式化字符串的新标准。我在将str.format() 与正则表达式一起使用时遇到了问题。
我编写了一个正则表达式来返回比指定域低一级的所有域或比指定域低两级的任何域,如果下面的第二级是 www...
假设指定的域是delivery.com,我的正则表达式应该返回a.delivery.com、b.delivery.com、www.c.delivery.com ...但它不应该返回xadelivery.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()?
【问题讨论】:
-
与问题没有直接关系,但通过养成在正则表达式中始终使用原始字符串的习惯,您以后会省去很多麻烦。
-
@Mark 这是什么原因?感谢您的提示。
-
作为一项规则,无论何时您在字符串文字中添加反斜杠,您都应该使用原始字符串。否则,您可能会遇到意外的字符串转义。这在 Windows 文件路径中最为明显,其中(非原始)“c:\names\bob”并不意味着您认为它的含义。在正则表达式中,使用原始字符串意味着您的正则表达式字符串就是您键入的内容。要匹配正则表达式中的单个反斜杠,您需要用另一个转义它:\\ 但是,非原始字符串中的序列会产生一个反斜杠,但从您的正则表达式来看并不明显。在原始字符串中,您的 r'\\' 按预期通过。
标签: python regex format string-formatting