如何将一个字符串与多个正则表达式匹配?

2024-10-01 15:50:14 发布

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

目前,我使用下面的过滤器来增加arr中的元素,给定一个字符串列表作为参数,在python中有没有一种有效的方法来实现这一点。在

  def countbycat(tempfilter):
        arr=[0,0,0,0,0]
        apattern,dpattern,mpattern,upattern,tpattern = re.compile("^[a]--*"),re.compile("^[d]--*"),re.compile("^[m]--*"),re.compile("^[u]--*"),re.compile("^[t]--*")
        for each in tempfilter:
            if upattern.match(each):
                 arr[0]+=1
            elif mpattern.match(each):
                 arr[1]+=1
            elif dpattern.match(each):
                 arr[2]=1
            elif apattern.match(each):
                 arr[3]+=1
            elif tpattern.match(each):
                 arr[4]+=1
        return arr  

Tags: 字符串re元素过滤器matcheacharrcompile
3条回答

对于问题中给出的正则表达式,可以使用以下正则表达式使用字符类:

[admut]-
  • [admut]将匹配admut
  • ^可以省略,因为re.match只在字符串的开头匹配。在
  • 删除了-*,因为它没有意义;只有一个-就足以检查-是否出现在a/d/m/u/t之后。在

而且,您可以使用字典而不是使用数组;无需记住索引:

^{pr2}$

您可以使用^{},而不是^{}。在

不要为此使用regex。你正在检查一个非常具体的固定条件。即each[1] == '-'和{}。这两种方法都比regex快得多。后者也可以用作映射。在

def countbycat(tempfilter):
  arr = [0, 0, 0, 0, 0]
  char_idx = {  # map admit to indices
    'u': 0,
    'm': 1,
    'd': 2,
    'a': 3,
    't': 4,
    }
  for each in tempfilter:
    if each[1] == '-':  # detect trailing -
      try:
        arr[char_idx[each[0]]] += 1  # increment position pointed to by admut
      except KeyError:  # each[0] not any of admut
        pass
  return arr  

在您的简单示例中,选择falsetru's answer

一般情况下,您可以将模式组合成一个正则表达式(前提是正则表达式不包含捕获组),然后检查哪个正则表达式匹配:

patterns = ["^[a]-+", "^[d]-+", "^[m]-+", "^[u]-+", "^[t]-+"]

complex_pattern = re.compile('|'.join(['(%s)' % i for i in patterns]))

# imperative way

arr = [0, 0, 0, 0, 0]

for each in tempfilter:
    match = complex_pattern.match(each)
    if match:
        arr[match.lastgroup + 1] += 1

return arr

# functional way

from collections import Counter

matches_or_none = (complex_pattern.match(each) for each in tempfilter)

return Counter(match.lastgroup + 1 for match in matches_or_none if match is not None)

相关问题 更多 >

    热门问题