user2050188 user2050188 - 1 year ago 100
Python Question

Python regular expression for extracting value of a key

I would like to extract value from a key=value pair (String) in Python, using regular expression (re.compile and match). I am new to Python. Any help appreciated...

Ex String:
[INFO] LICENSE=abcd-efgh-1234-34ki
I want the value of LICENSE i.e abcd-efgh-1234-34ki

I tried the below, but it is not exactly working
license_regex = re.compile('.LICENSE=.?.*')
match = license_regex.match(line)

=> prints the whole line.
then I tried with (.?)!.' => doesn't print anything


Answer Source



then the captured group will have the desired portion.

  • ^.*? lazily matches upto a empty string followed by LICENSE=

  • (.*) matches the rest, and put in captured group 1


In [2]: s = '[INFO] LICENSE=abcd-efgh-1234-34ki'

In [3]:'^.*?\bLICENSE=(.*)', s).group(1)
Out[3]: 'abcd-efgh-1234-34ki'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download