在Python正则表达式中使用变量

2024-06-06 21:05:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析一个文件,并在行中查找username-#,其中用户名将更改,破折号后面可以有任意数字[0-9]

我尝试过几乎所有的组合,试图在正则表达式中使用变量username

我是不是和re.compile('%s-\d*'%user)这样的事情很接近?


Tags: 文件用户reusername数字事情compileuser
3条回答

是的,您可以自己连接regex,或者使用字符串格式。但是,如果变量可以包含在正则表达式中具有特殊意义的字符,请不要忘记使用re.escape()

按部就班地工作:

>>> user = 'heinz'
>>> import re
>>> regex = re.compile('%s-\d*'%user)
>>> regex.match('heinz-1')
<_sre.SRE_Match object at 0x2b27a18e3f38>
>>> regex.match('heinz-11')
<_sre.SRE_Match object at 0x2b27a2f7c030>
>>> regex.match('heinz-12345')
<_sre.SRE_Match object at 0x2b27a18e3f38>
>>> regex.match('foo-12345')

可以使用string的.format()方法创建字符串:

re.compile('{}-\d*'.format(user))

相关问题 更多 >