使用 re.findall() 和 re.escape() 匹配包含元字符的字符串?
Matching string that contain Metacharacters with re.findall() and re.escape()?
匹配包含元字符的句子的正则表达式是什么?
关注 senario :
我有一个字符串:line = "He finally answer (after taking time to think (5 minutes) * sighs ; end)"
我要匹配句子的这一部分:line2 = "after taking time to think (5 minutes) * sighs ; end"
但我不想使用正则表达式来查找括号内的元素
为此,我正在使用:re.findall(re.escape(line2), re.escape(line))
但我得到的结果是空的
无需对文本(在本例中为变量 line)执行转义方法,您提供:
import re
line = "He finally answer (after taking time to think (5 minutes) * sighs ; end)"
line2 = "after taking time to think (5 minutes) * sighs ; end"
result = re.findall(re.escape(line2), line)
print(result) # ['after taking time to think (5 minutes) * sighs ; end']
匹配包含元字符的句子的正则表达式是什么?
关注 senario :
我有一个字符串:line = "He finally answer (after taking time to think (5 minutes) * sighs ; end)"
我要匹配句子的这一部分:line2 = "after taking time to think (5 minutes) * sighs ; end"
但我不想使用正则表达式来查找括号内的元素
为此,我正在使用:re.findall(re.escape(line2), re.escape(line))
但我得到的结果是空的
无需对文本(在本例中为变量 line)执行转义方法,您提供:
import re
line = "He finally answer (after taking time to think (5 minutes) * sighs ; end)"
line2 = "after taking time to think (5 minutes) * sighs ; end"
result = re.findall(re.escape(line2), line)
print(result) # ['after taking time to think (5 minutes) * sighs ; end']