Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex for extracting strings between certain two strings

Tags:

python

regex

Let's assume I have a string

st = "'aaa': '1', 'bbb': '2.3', 'ccc': 'name'"

I want to extract from st the following

['1', '2.3', 'name']

How can I do this?

Thanks

like image 675
Mansumen Avatar asked Feb 17 '26 06:02

Mansumen


2 Answers

You can first create dict by ast.literal_eval and then get values:

import ast

st = "'aaa': '1', 'bbb': '2.3', 'ccc': 'name'"

print (ast.literal_eval('{' + st + '}'))
{'aaa': '1', 'bbb': '2.3', 'ccc': 'name'}

#python 3 add list
print (list(ast.literal_eval('{' + st + '}').values()))
['1', '2.3', 'name']

#python 2
print ast.literal_eval('{' + st + '}').values()
['1', '2.3', 'name']
like image 163
jezrael Avatar answered Feb 19 '26 19:02

jezrael


Doing it with ast module would be best, like jezrael did it. Here is another solution with regex:

import re

st = "'a': '1', 'b': '2.3', 'c': 'name', 'd': 229, 'e': '', 'f': '228', 'g': 12"
print re.findall(r'\'\S+?\':\s*\'?(.*?)\'?(?:,|$)', st)

Output:

['1', '2.3', 'name', '229', '', '228', '12']

Demo on regex101:

https://regex101.com/r/zGAt4D/5

like image 29
Mohammad Yusuf Avatar answered Feb 19 '26 18:02

Mohammad Yusuf



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!