Javascript Regular Question Answer Returns part of the matched expression as follows: "No, because compilation breaks the connection between the regular expression text and the matching logic."
But Python saves Match Objects , and re.groups()
returns the specific group (s) that caused the match. It should be simple to save the regular expression text of each group as part of the matching object and return it, but it doesn't seem to be a challenge.
import re pat = "(^\d+$)|(^\w+$)|(^\W+$)" test = ['a', 'c3', '36d', '51', '29.5', '#$%&'] for t in test: m = re.search(pat, t) s = (m.lastindex, m.groups()) if m else '' print(str(bool(m)), s)
This returns:
True (2, (None, 'a', None)) True (2, (None, 'c3', None)) True (1, ('51', None, None)) False True (3, (None, None, '#$%&'))
The compiler obviously knows that there are three groups in this template. Is there a way to extract the subpattern in each group in a regular expression with something like:
>>> print(m.regex_group_text) ('^\d+$', '^\w+$', '^\W+$')
Yes, you could write your own pattern, for example, to divide it by '|' for this particular model. But it would be much simpler and more reliable to use compiler comprehension of the text in each group.