⊗pyPmREMSeP 53 of 128 menu

Pockets in Python's search method

Often when searching for a match, it is convenient to break the substring into so-called pockets. They are a way to break the match into separate parts. To use them, you need to enclose part of the regular expression in parentheses.

Let's try it in practice. Let's say we have the following line:

txt = '123 456'

Let's sort the substrings with numbers into pockets. To do this, we'll write the following regular expression:

res = re.search('(\d+) (\d+)', txt)

As a result, we will get a match object. Its element with index 1 will contain the first pocket, the element with index 2 will contain the second pocket, and the element with index 0 will contain everything found (the so-called zero pocket):

print(res[0]) # '123 456' - found print(res[1]) # '123' - 1 pocket print(res[2]) # '456' - 2 pocket

Given a string containing a domain:

txt = 'sss domain.ru zzz'

Find this domain and put its name in the first pocket and the zone in the second.

Given a string containing a date:

txt = '31.12.2025'

Place the day in the first pocket, the month in the second, and the year in the third.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline