我知道有一些关于将字符串转换为原始字符串字符串的帖子,但它们都不能帮助我解决问题。将用户输入字符串转换为原始字符串文字以构造正则表达式
我的问题是:
说,例如,我想知道模式“\节”是在文本“ABCD \ sectiondefghi”。当然,我可以这样做:
import re
motif = r"\\section"
txt = r"abcd\sectiondefghi"
pattern = re.compile(motif)
print pattern.findall(txt)
这会给我我想要的。但是,每次我想在新文本中找到新模式时,我都必须更改令人痛苦的代码。因此,我想写的东西更灵活,像这样(test.py):
import re
import sys
motif = sys.argv[1]
txt = sys.argv[2]
pattern = re.compile(motif)
print pattern.findall(txt)
然后,我想在终端像这样运行:
python test.py \\section abcd\sectiondefghi
但是,这是行不通的(我讨厌使用\\\\section
)。
那么,有没有办法将我的用户输入(从终端或从文件)转换为python原始字符串?或者是否有更好的方式从用户输入中进行正则表达式模式编译?
非常感谢。
另一方面,如果你正在寻找文字字符串,重新是错误的工具。 – Fredrik
@Fredrik:我认为这将成为更大模式的一部分,而OP只是简化了。 –
@MartijnPieters谢谢,re.escape确实有帮助! – dbrg77