Anna Jeanine Anna Jeanine - 16 days ago 5
Python Question

Python: Regular Expression pattern can occur multiple times but is NOT conditional

Hi everyone! I am having trouble formatting a regex in

Python
. What I would like the regex to find is
_D
, but after this a
D
or
2
can follow. But this pattern of
(D|2)
can occur multiple times (or, not at all). The regex which I am using now is:

re.search('_D(D|2)*', variable)


I have tried:

re.search('_D(D|2)(D|2)*', variable)


But this didn't work for me either. Could someone help me out to make the pattern optional but multiple times?

Answer

The * suffix means "0 or more times" and therefore already implies optionality. You want to put it after (D|2) for that group to be repeatable:

re.search('_D(D|2)*', variable)