将命令行参数转换为正则表达式

dbr*_*g77 14 python regex shell

比方说,我想知道模式"\ section"是否在文本"abcd\sectiondefghi"中.当然,我可以这样做:

import re

motif = r"\\section"
txt = r"abcd\sectiondefghi"
pattern = re.compile(motif)
print pattern.findall(txt)
Run Code Online (Sandbox Code Playgroud)

这会给我我想要的东西.但是,每次我想在新文本中找到新模式时,我都必须更改令人痛苦的代码.因此,我想写一些更灵活的东西,比如this(test.py):

import re
import sys

motif = sys.argv[1]
txt = sys.argv[2]
pattern = re.compile(motif)
print pattern.findall(txt)
Run Code Online (Sandbox Code Playgroud)

然后,我想在终端中运行它,如下所示:

python test.py \\section abcd\sectiondefghi
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用(我讨厌使用\\\\section).

那么,有没有办法将我的用户输入(从终端或从文件)转换为python原始字符串?或者是否有更好的方法从用户输入进行正则表达式模式编译?

非常感谢你.

Mar*_*ers 27

用于re.escape()确保输入文本在正则表达式中被视为文字文本:

pattern = re.compile(re.escape(motif))
Run Code Online (Sandbox Code Playgroud)

演示:

>>> import re
>>> motif = r"\section"
>>> txt = r"abcd\sectiondefghi"
>>> pattern = re.compile(re.escape(motif))
>>> txt = r"abcd\sectiondefghi"
>>> print pattern.findall(txt)
['\\section']
Run Code Online (Sandbox Code Playgroud)

re.escape()逃避所有非字母数字; 在每个这样的字符前面添加一个反斜杠:

>>> re.escape(motif)
'\\\\section'
>>> re.escape('\n [hello world!]')
'\\\n\\ \\[hello\\ world\\!\\]'
Run Code Online (Sandbox Code Playgroud)

  • 另一方面,如果您正在搜索文字字符串,则re是错误的工具. (2认同)