Python 正则表达式:分组中的分组?
我有一些这样的字符串
s = 'MR1|L2-S1x'
这些字符串的模式总是一样的:一个或两个字符,后面可以跟一个数字和一个分隔符,分隔符可以是 [|.+:x-]
中的任意一个。这个模式可以重复出现,最多可以出现6次。
所以,匹配的模式是很清楚的。
p = r'([A-Z]+)(\d)?([|.+:x-]+)'
但是,怎么才能把它作为一组中的一组来匹配呢?
更准确地说:现在我得到的是
t=re.search(p,s)
t.groups()
('MR', '1', '|')
不过,我想要的是
('MR', '1', '|'),('L', '2', '-'),('S', '1', 'x')
2 个回答
2
import re
tokens=[]
subject = "MR1|L2-S1xZZ+"
reobj = re.compile(r"([A-Z]{1,2})(\d?)([|.+:x-]?)")
for match in reobj.finditer(subject):
tokens.append((match.group(1),match.group(2),match.group(3)))
print(tokens)
输出:
[('MR', '1', '|'), ('L', '2', '-'), ('S', '1', 'x'), ('ZZ', '', '+')]
1
用户“undefined is not a function”(在评论中)说得对。可以使用 findall 来获取所有匹配的组。
Python 2.7.4 (default, Apr 6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'MR1|L2-S1x'
>>> p = r'([A-Z]+)(\d)?([|.+:x-]+)'
>>> import re
>>> t = re.findall(p, s)
>>> t
[('MR', '1', '|'), ('L', '2', '-'), ('S', '1', 'x')]
>>>