我有正则表达式,它在括号之间打印,实际上我只需要特定的括号,我的意思是
car(skoda,audi)
bike(hayabusa)
我得到的输出是: 斯柯达 奥迪 隼鸟
为了得到括号中的汽车和自行车,我使用了:(r'^(\S+)\((.*)\)$')
但我只需要在“车(…)”里找到车,具体来说,怎么办?你知道吗
我试过:(r'^car(\S+)\((.*)\)$')
我只需要skoda,audi
而不是隼鸟
我没有得到输出
要使用的编码:
class Group:
def __init__(self):
self.members = []
self.text = []
with open('text1.txt') as f:
groups = collections.defaultdict(Group)
group_pattern = re.compile(r'^(\S+)\((.*)\)$') #<=here i am using
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
else:
if (current_group is not None) and (len(line) > 0):
groups[current_group].text.append(line)
for group_name, group in groups.items():
print "%s(%s)" % (group_name, ','.join(group.members))
print '\n'.join(group.text)
你可以试试Positive Lookbehind & Lookahead
online demo
或者使用
findall
从索引1中获取匹配的组online demo
示例代码:
你的代码怎么了?你知道吗
代码与预期字符串匹配的原因是
(\S+)
更改为(\S*)
,因为\S+
执行贪婪操作匹配。那个它和最后一个匹配。因此不会发生捕获。你知道吗最后你的正则表达式是
获取组索引2中的字符串。你知道吗
相关问题 更多 >
编程相关推荐