举例来说,我想知道模式“ \ section”是否在文本“ 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原始字符串?还是有更好的方法根据用户输入进行正则表达式模式编译?
非常感谢你。
用于re.escape()
确保在正则表达式中将输入文本视为文字文本:
pattern = re.compile(re.escape(motif))
演示:
>>> import re
>>> motif = r"\section"
>>> txt = r"abcd\sectiondefghi"
>>> pattern = re.compile(re.escape(motif))
>>> txt = r"abcd\sectiondefghi"
>>> print pattern.findall(txt)
['\\section']
re.escape()
转义所有非字母数字;在每个这样的字符前面添加反斜杠:
>>> re.escape(motif)
'\\\\section'
>>> re.escape('\n [hello world!]')
'\\\n\\ \\[hello\\ world\\!\\]'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句