【问题标题】:grouping using regex ending with colon ':'使用以冒号 ':' 结尾的正则表达式进行分组
【发布时间】:2014-08-30 14:51:20
【问题描述】:

我有一个代码,用于对括号内的单词进行分组,如果括号前有相同的名称。

例如:

car __name__(skoda,audi)
car __name__(benz)

输出:

car __name__(skoda,audi,benz)

但是当末尾提供冒号:时,它不会输出,

car __name__(skoda,audi):       =>no output prints with :
car __name__(benz):

我认为问题出在我的正则表达式上

我的代码:

import collections
class Group:
    def __init__(self):
        self.members = []
        self.text = []
with open('out.txt','r') as f:
    groups = collections.defaultdict(Group)
    group_pattern = re.compile(r'(\S+(?: __[^__]*__)?)\((.*)\)$')
    current_group = None
    for line in f:
        line = line.strip()
        m = group_pattern.match(line)
        if m:    # this is a group definition line
            group_name, group_members = m.groups()
            groups[group_name].members.extend(group_members.split(','))
            current_group = group_name
for group_name, group in groups.items():
      print "%s(%s)" % (group_name, ','.join(group.members))

【问题讨论】:

    标签: python regex


    【解决方案1】:

    在正则表达式中,只需在最后添加 : 并通过在冒号旁边添加 ? 使其成为可选,以便它匹配两种类型的字符串格式。

    (\S+(?: __[^__]*__)?)\((.*)\):?$
    

    DEMO

    【讨论】:

      【解决方案2】:

      问题是您的正则表达式末尾有一个 $。这会强制正则表达式查找以括号结尾的模式。

      您可以通过在正则表达式中删除 $ 来解决它(如果您认为会有其他尾随字符):

      (\S+(?: __[^__]*__)?)\((.*)\)
      

      或者您可以调整正则表达式以在模式中包含冒号出现 0 或 1 次的可能性:

      (\S+(?: __[^__]*__)?)\((.*)\):?$
      

      【讨论】:

        【解决方案3】:

        你可以不用正则表达式来做到这一点:

        f = [ 'car __name__(skoda,audi):\n', 'car __name__(benz):\n' ]
        groups = {}
        for line in f:
            v =  line.strip().split('__')
            gname, gitems = v[1], v[2]
            gitems = gitems.strip("():").split(",")
            groups[gname] = groups.get(gname, []) + gitems
        print groups
        

        【讨论】:

          猜你喜欢
          • 2020-03-28
          • 1970-01-01
          • 1970-01-01
          • 2021-03-12
          • 2011-04-13
          • 2020-09-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多