gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:12:01 25 4
gpt4 key购买 nike

例如,我想知道模式“\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\\!\\]'

关于python - 将命令行参数转换为正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17830198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com