正则表达式获得subgoups

时间:2017-04-01 09:34:42

标签: python regex

我遇到了以下问题:

SELECT * FROM Person p
WHERE NOT EXISTS (SELECT g.id FROM Goal g WHERE g.goals="AAA" AND g.idPerson=p.id)

结果是:

change = "1,23 2,54 1,85 "
results = re.findall(r"((\d+),(\d+) )+((\d+),(\d+) )+", change)
print(results)

但我想要这样的事情:

('2,54 ', '2', '54', '1,85 ', '1', '85')

遗憾的是我没有找到任何解决方案

2 个答案:

答案 0 :(得分:2)

重复正则表达式组是多余的。您应该只使用1并执行findall。我已经使用了itertools.chain,但你也可以通过简单的列表理解来实现它。

change = "1,23 2,54 1,85 "
results = re.findall(r"((\d+),(\d+) )", change)
print(results)
# [('1,23 ', '1', '23'), ('2,54 ', '2', '54'), ('1,85 ', '1', '85')]
from itertools import chain
print(list(chain(*results)))
# ['1,23 ', '1', '23', '2,54 ', '2', '54', '1,85 ', '1', '85']
# simple list comprehension
print([single for group in results for single in group])
# ['1,23 ', '1', '23', '2,54 ', '2', '54', '1,85 ', '1', '85']

答案 1 :(得分:0)

使用以下方法:

change = "1,23 2,54 1,85 "
results = [n for t in re.findall(r"((\d+),(\d+))", change) for n in t]
print(results)

输出:

['1,23', '1', '23', '2,54', '2', '54', '1,85', '1', '85']