gpt4 book ai didi

python - 包含字符串和传统正则表达式的列表

转载 作者:行者123 更新时间:2023-12-01 05:44:03 24 4
gpt4 key购买 nike

我正在编写一个脚本来检查目录中文件的内容。到目前为止,我得到的是一个包含各种字符串的列表,并且还想在搜索中包含传统的正则表达式。这是我到目前为止所拥有的:

regex = [ "STRING1", "STRING2", "STRING3", (?:<my regex here>)]
pattern = re.compile(regex)

我遇到了各种错误,并尝试解决一些问题,在正则表达式中添加 r' ,在编译函数中使用 .join() ,显然我做错了一些事情。代码正确执行,但在应该时找不到匹配项,所以显然我的正则表达式编译不正确。那么,创建我想要使用的正则表达式列表,然后在搜索中迭代该列表的正确方法是什么?

最佳答案

你想做这样的事情吗?:

import re

# Pre-compile the patterns
regexes = [ re.compile(p) for p in [ 'this',
'that',
]
]
text = 'Does this text match the pattern?'

for regex in regexes:
print 'Looking for "%s" in "%s" ->' % (regex.pattern, text),

if regex.search(text):
print 'found a match!'
else:
print 'no match'

取自PyMOTW .

关于python - 包含字符串和传统正则表达式的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16720103/

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