r/pythonhelp • • Aug 21 '22

re.findall( regex ) find every parentheses with remix, mix or edit inside

re.findall( r"\(.*?\) title )

this prints every parentheses, so far so good.

re.findall( r"\(.*?remix.*?\) title )
( bla bla ) ( bla bla remix )

this matches matches multiple parentheses

re.findall( r"\(.*?(remix|mix|edit).*?\) title )

only prints the word remix, mix or edit but not the rest of inside.

2 Upvotes

6 comments sorted by

1

u/throwaway8u3sH0 Aug 21 '22

I think you need to surround the section you want to capture with parentheses.

Also, a star is "zero or more", so the question marks might be redundant.

1

u/sneekyleshy Aug 21 '22

sorry not quite sure what you mean. there can be text before and after the words im looking for.

1

u/throwaway8u3sH0 Aug 21 '22

Wrt to the .*?, the star means means "0 or more", (as opposed to a plus sign, which means 1 or more). So .* will match anything, including nothing, so the question mark is probably redundant.

1

u/sneekyleshy Aug 21 '22

if i omit the ? in the first example it would find anything. ? is also used to say if its greedy. but im very confused, i def need to read more, how do i find which version or type of regex the re module uses?

1

u/throwaway8u3sH0 Aug 21 '22

Oh, you're totally right about the non-geedy. My bad. I forgot that it could be used that way.

The Python regex docs allow you to select the version at the top. Whatever python --version shows is what you got.

1

u/throwaway8u3sH0 Aug 21 '22

When writing regex, you can choose a subset of it that's "captured" when it matches. So like super([a-z]+) will match "superman" and "superhero", but it will return just "man" or "hero". You can have multiple capture groups, and in some advanced regex even refer to previous ones -- really good when trying to do a dynamic find/replace.

Take a look here for more info: https://pynative.com/python-regex-capturing-groups/

You'll want to make sure there's a capture group for the portion of regex you want to work with.