条件语句中的Python正则表达式匹配

2024-10-01 11:41:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析文件,我想检查每一行与几个复杂的regex。像这样的东西

if re.match(regex1, line): do stuff
elif re.match(regex2, line): do other stuff
elif re.match(regex3, line): do still more stuff
...

当然,要做这些,我需要匹配对象。我只能想到三种可能性,每一种都留下一些需要的东西。

if re.match(regex1, line): 
    m = re.match(regex1, line)
    do stuff
elif re.match(regex2, line):
    m = re.match(regex2, line)
    do other stuff
...

这需要进行两次复杂的匹配(这是长文件和长regex:/)

m = re.match(regex1, line)
if m: do stuff
else:
    m = re.match(regex2, line)
    if m: do other stuff
    else:
       ...

我越陷越深,情况就越糟。

while True:
    m = re.match(regex1, line)
    if m:
        do stuff
        break
    m = re.match(regex2, line)
    if m:
        do other stuff
        break
    ...

看起来很奇怪。

正确的方法是什么?


Tags: 文件reifmatchlinedoelseregex
3条回答

您可以为每个正则表达式所需的操作定义一个函数,并执行如下操作

def dostuff():
    stuff

def dootherstuff():
    otherstuff

def doevenmorestuff():
    evenmorestuff

actions = ((regex1, dostuff), (regex2, dootherstuff), (regex3, doevenmorestuff))

for regex, action in actions:
    m = re.match(regex, line)
    if m: 
        action()
        break
for patt in (regex1, regex2, regex3):
    match = patt.match(line)
    if match:
        if patt == regex1:
            # some handling
        elif patt == regex2:
            # more
        elif patt == regex3:
            # more
        break

我喜欢Tim的答案,因为它将每个regex匹配的代码分开,以保持简单。对于我的答案,我不会为每个匹配项放置超过一两行的代码,如果需要更多,请调用单独的方法。

首先,您真的需要使用regexp进行匹配吗?在perl中使用regexp的地方,我经常使用python中的字符串函数(find、startswith等)。

如果确实需要使用regexps,可以使用一个简单的搜索函数来执行搜索,如果返回匹配项,则在返回True之前设置一个store对象来保持匹配。

例如

def search(pattern, s, store):
    match = re.search(pattern, s)
    store.match = match
    return match is not None

class MatchStore(object):
    pass   # irrelevant, any object with a 'match' attr would do

where = MatchStore()
if search(pattern1, s, where):
    pattern1 matched, matchobj in where.match
elif search(pattern2, s, where):
    pattern2 matched, matchobj in where.match
...

相关问题 更多 >