kliao kliao - 24 days ago 19
Python Question

Dynamically Naming Groups in Python Regular Expressions

Is there a way to dynamically update the name of regex groups in Python?

For example, if the text is:

person 1: name1
person 2: name2
person 3: name3
...
person N: nameN


How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand how many people there are?

Answer

No, but you can do something like this:

>>> import re
>>> p = re.compile('(?m)^(.*?)\\s*:\\s*(.*)$')
>>> text = '''person 1: name1
person 2: name2
person 3: name3
...
person N: nameN'''
>>> p.findall(text)

output:

[('person 1', 'name1'), ('person 2', 'name2'), ('person 3', 'name3'), ('person N', 'nameN')]

A quick explanation:

(?m)     # enable multi-line mode
^        # match the start of a new line
(.*?)    # un-greedily match zero or more chars and store it in match group 1
\s*:\s*  # match a colon possibly surrounded by space chars
(.*)     # match the rest of the line and store it in match group 2
$        # match the end of the line

References

Comments