我希望使用正则表达式来提取出现在两个字符串之间的文本。如果我想每次都在相同的字符串之间提取数据(以及无数问题,例如 Regex matching between two strings? ),我知道该怎么做,但我想使用变化的变量来做到这一点,并且它们本身可能在 Regex 中包含特殊字符。 (我想要任何特殊字符,例如 * 被视为文本)。
例如,如果我有:
text = "<b*>Test</b>"
left_identifier = "<b*>"
right_identifier = "</b>
我想创建正则表达式代码,这将导致运行以下代码:
re.findall('<b\*>(.*)<\/b>',text)
它是 <b\*>(.*)<\/b>
我不知道如何动态创建的部分。
最佳答案
你可以这样做:
import re
pattern_string = re.escape(left_identifier) + "(.*?)" + re.escape(right_identifier)
pattern = re.compile(pattern_string)
转义函数会自动转义特殊字符。例如:
>>> import re
>>> print re.escape("<b*>")
\<b\*\>
关于python - 在两个字符串(它们是变量)之间提取的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656527/