繁体   English   中英

如何在python中使用变量代替字符串内的正则表达式搜索函数中的字符串

[英]how to use a variable instead of a string inside regex search function in python

我有这个正则表达式函数来提取字符串中的特定单词

fileName = re.search(r'path1\w([A-Za-z\d]+)', self.fileList[0]).group(1)

path1是一个实际的字符串

如果我想用fileName变量替换它,其中fileName = "path1"

我试过了:

print re.search(r'\w([A-Za-z\d]+)' % fileName, self.fileList[0]).group(1)

我收到了这个错误:

TypeError:并非在字符串格式化期间转换所有参数

为什么我会收到此错误? 如何解决这个问题呢

你的正则表达式需要%s

print re.search(r'%s\w([A-Za-z\d]+)' % fileName, self.fileList[0]).group(1)

或者作为更加pythoinc和灵活的方式,您可以使用str.format函数:

print re.search(r'{}\w([A-Za-z\d]+)'.format(fileName), self.fileList[0]).group(1)

请注意,如果您有一个文件名列表,您可以循环它们并将文件名传递给format ,这是第二种方式。

将字符串插入像Regex这样的语言时应该非常小心。 在这种情况下,您可能应该首先转义字符串:

expression = r'{}\w([A-Za-z\d]+)'.format(re.escape(fileName))
re.search(expression, self.fileList[0]).group(1)

也许值得注意正则表达式的命名列表:

import regex

expression = regex.compile(r'\L<filename>\w([A-Za-z\d]+)', filename=[fileName])
expression.search(self.fileList[0]).group(1)

这避免了必须regex-escape文字,并且如果有多个选项,则效果更好。 (无论如何,加上regex更好,所以更有理由使用它!)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM