Search

29 August, 2018

Python: Saving regular expression results in variables directly

Python Regular expressions has a powerful tools under it's regular expressions module which lets you create variables and save your search results directly.

It is called named groups . When you search for something and you want to save it in a variable when found, this is what you should use.



Let's see some examples:

string = 'AB_1_20_12_HD'

String Details:


First : AB (This is a sample category..like AB, CD, EF)
Second: 1_20_12 (This is the version.)
Third: HD (This is lets assume a video format like HD, Cam, BR etc)

Goal : We want to capture all three params using one regex.



>>> string
'AB_1_20_12_HD'

>>> rr = re.search('(?P<Sample>(AB|CD|EF)+)[_]*(?P<Version>\d+_\d+_\d+)[_]*(?P<Video>[a-zA-Z]*)', string)

>>> rr.group('Version')
'1_20_12'
>>> rr.group('Sample')
'AB'
>>> rr.group('Video')
'HD'


No comments:

Post a Comment