Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex findall OR [duplicate]

Tags:

python

regex

I am compiling the following pattern:

pattern = re.compile("media.+\.(aac|ts)")

My idea is to obtain .ts and .aac media files contained in a string. The media file names can be media-u9xuxtkay_213.aac or media-u9xuxtkay_213.ts

According to this accepted answer Python regular expressions OR you can use ( | ) as an OR But I dont see how that's an accepted answer since it doenst seem to work to me:

In [23]: s
Out[23]: 'Sent from my iPhone'

In [24]: patt = re.compile("Sent from my (iPhone|iPod)")

In [25]: patt.findall(s)
Out[25]: ['iPhone']

So I call the findall and I get this:

In [37]: media
Out[37]: 'media-u9xuxtkay_213.aac'

In [38]: pattern = re.compile("media.+\.(aac|ts)")

In [39]: pattern.findall(media)
Out[39]: ['aac']

I should get a media-u9xuxtkay_213.aac instead just aac. The same way the accepted answer should return Sent from my iPhone instead just iPhone

like image 520
lapinkoira Avatar asked Mar 24 '26 15:03

lapinkoira


1 Answers

The parentheses act as a "capture group", denoting what the regex should select from the string. You can use (?: ) to make it a non-capturing group, so it gets the whole string instead.

re.compile(r"media.+\.(?:aac|ts)")
like image 110
ASGM Avatar answered Mar 26 '26 05:03

ASGM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!