user2050188 user2050188 - 1 month ago 10
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

Thanks

Answer

Do:

^.*?\bLICENSE=(.*)

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

Example:

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

In [3]: re.search(r'^.*?\bLICENSE=(.*)', s).group(1)
Out[3]: 'abcd-efgh-1234-34ki'
Comments