Home > Enterprise >  Is there a method to get all groups in regular expression with wildcard in python
Is there a method to get all groups in regular expression with wildcard in python

Time:07-07

Just like the follow code, there is not all groups. Is there a method to get all groups? Thanks~

import re

res = re.match(r'(?: ([a-z] ) ([0-9] ))*', ' a 1 b 2 c 3')

# echo ('c', '3'), but I want ('a', '1', 'b', '2', 'c', '3')
res.groups()

CodePudding user response:

You could use re.finditer to iterate the matches, appending each result to an empty tuple:

import re

res = tuple()
matches = re.finditer(r' ([a-z] ) ([0-9] )', ' a 1 b 2 c 3')
for m in matches:
    res = res   m.groups()

Output:

('a', '1', 'b', '2', 'c', '3')

Note that in the regex the outer group is removed as it is not required with finditer.

CodePudding user response:

You are repeating a capture group, which gives you the value of the last iteration which is ('c', '3')

You can repeat the pattern to check if the whole string if of that format, and then split on a space and wrap it in a tuple.

import re

m = re.match(r"(?: [a-z]  [0-9] )*$", " a 1 b 2 c 3")
if m:
    print(tuple(m.group().split()))

Output

('a', '1', 'b', '2', 'c', '3')
  • Related