⊗pyPmRENPB 70 of 128 menu

Non-preserving parentheses in Python regular expressions

The brackets ( ) perform two functions - grouping symbols and the pocket function. But what to do if you need to group, but not put in the pocket? To solve this problem, special non-preserving brackets (?: ) - they group but do not pocket.

Example

In the following example, we need the first brackets for grouping, and the second for the pocket. However, both brackets save data to the pocket:

txt = 'abab123' res = re.search('(ab)+([1-9]+)', txt)

As a result, we will have the following in our pockets:

print(res[0]) # 'abab123' print(res[1]) # 'ab' print(res[2]) # '123'

Example

Let's make it so that the first pair of brackets only groups, but does not put it in the pocket:

txt = 'abab123' res = re.search('(?:ab)+([1-9]+)', txt)

As a result, our number will be in the first pocket:

print(res[1]) # '123'
enru