1

I have this line of code:

hdfs_regex = re.compile(r'\s+(?P<unmatched>\d+)\s+\/\s+(?P<total>\d+)')

I run through a file and use:

results = re.search(hdfs_regex, line)

to look for the portion in the line that matches my regex. Upon match, is there a way to return each found matched regex variable?

Is there away to return ever found group without knowing the regex variable name?

Pseudocode would might look something like this

grouped_val = [i for i in results.grouped()]

where results.grouped() is an iterable that I can use to retrieve the found value without knowing the variable name

1 Answer 1

2

You can use groups() that return a tuple containing all the subgroups of the matched patterns :

>>> m = re.search(r"(\d+)\.?(\d+)?", "24.13244")
>>> m.groups()
('24', '13244')

groups([default]) Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. (Incompatibility note: in the original Python 1.5 release, if the tuple was one element long, a string would be returned instead. In later versions (from 1.5.1 on), a singleton tuple is returned in such cases.)

Sign up to request clarification or add additional context in comments.

1 Comment

Just what I needed thanks! will accept when allowed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.