【问题标题】:List containing strings and traditional regular expressions包含字符串和传统正则表达式的列表
【发布时间】:2013-05-19 04:15:33
【问题描述】:

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

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

我遇到了各种错误,并尝试了一些故障排除,将 r' 添加到正则表达式,在编译函数中使用 .join() ,显然我做错了什么。代码正确执行,但没有找到匹配项,所以很明显我的正则表达式编译不正确。那么,列出我要使用的正则表达式,然后在搜索中遍历该列表的正确方法是什么?

【问题讨论】:

  • 我想你可能需要加入这个列表,就像这个答案stackoverflow.com/a/3040797/264775
  • 嗨,欢迎来到 StackOverflow。请使用标签,不要在标题前添加语言。
  • 你希望你的例子匹配什么?

标签: python regex list


【解决方案1】:

您是否正在尝试做这样的事情?:

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。

【讨论】:

    猜你喜欢
    • 2011-06-27
    • 1970-01-01
    • 2011-07-22
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2016-04-21
    相关资源
    最近更新 更多