我有一个代码,它用来分组的话里面的偏执,如果它有一个相同的名字前偏执。你知道吗
例如:
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))
在regex中,只需在最后添加
:
,并通过在冒号旁边添加?
使其成为可选的,这样它就可以匹配这两种类型的字符串格式。你知道吗DEMO
您可以在不使用正则表达式的情况下执行此操作:
问题是在正则表达式的末尾有一个$。这迫使正则表达式寻找以括号结尾的模式。你知道吗
您可以通过在正则表达式中删除$来解决此问题(如果您认为会有其他尾随字符):
或者可以调整正则表达式,使其在模式中包含冒号出现0或1次的可能性:
相关问题 更多 >
编程相关推荐