⊗pyPmRESNP 56 of 128 menu

Named pockets in Python's search method

To make working with pockets more convenient, you can give them names. To do this, in the first parameter of the search method, before the regular expression designation, the string '?P' is written, after which the pocket name is indicated in angle brackets.

Such pockets can be obtained using the groupdict method. It will output them as a dictionary, where the key is the name of the pocket and the value is a substring lying in it.

Let's look at working with named pockets using an example. Let's say we have a string:

txt = '123 456'

Let's make two pockets for it, which will be called 'num1' and 'num2' respectively:

res = re.search('(?P<num1>\d+)\s(?P<num2>\d+)', txt)

Now let's derive our pockets using the groupdict method:

print(res.groupdict()) # {'num1': '123', 'num2': '456'}

Given a line with time:

txt = '12:59:59'

Place hours, minutes and seconds in separate named pockets.

Given a string:

txt = 'aaa bbb 123 456'

Put the substrings 'aaa' and 'bbb' into separate named pockets.

Given a string:

txt = 'alex23'

Place the user's name and age in separate named pockets.

enru