我有一个多行正则表达式,我想使用字符串格式来动态填充正则表达式的某些部分。例:
foo = 'Please feed {me} some pistachio ice cream!'
r = re.compile('Please feed {{{}}} '.format('me')
'some {} ice cream!'.format('pistachio'))
r.findall(foo)
这引发了语法错误:
>>> foo = 'Please feed {me} some pistachio ice cream!'
>>> r = re.compile('Please feed {{{}}} '.format('me')
... 'some {} ice cream!'.format('pistachio'))
File "<stdin>", line 2
'some {} ice cream!'.format('pistachio'))
^
SyntaxError: invalid syntax
这是一个人为的例子,但假设我有一个很长的正则表达式模式分成多行以提高可读性。如何任意设置一行或多行的字符串格式?
这是一个 Python 语法问题,而不是正则表达式问题。未调用 re.compile()
函数,因为您犯了语法错误。不能将隐式字符串串联(其中两个直接相邻的字符串文本自动联接到一个字符串对象中)与.format()
这样的调用一起使用。
要么将.format()
放在末尾,要么使用 +
显式连接:
# one string, on two lines, implicitly concatenated then formatted
r = re.compile('Please feed {{{}}} '
'some {} ice cream!'.format('me', 'pistachio'))
# two strings, concatenated explicitly after formatting
r = re.compile('Please feed {{{}}} '.format('me') +
'some {} ice cream!'.format('pistachio'))
我还删除了反斜杠,否则模板中将无法正确加倍
{{
和}}
字符。
演示,(没有re.compile
调用,因为这不是这里的问题):
>>> ('Please feed {{{}}} '
... 'some {} ice cream!'.format('me', 'pistachio'))
'Please feed {me} some pistachio ice cream!'
>>> ('Please feed {{{}}} '.format('me') +
... 'some {} ice cream!'.format('pistachio'))
'Please feed {me} some pistachio ice cream!'