How can I use regex to get a list of all values in double quotes and true and false which dont have quotes?
For example:
string = '"hi you, sir", true false, "come, here"'
to
lst = ["hi you, sir", true, false, "come, here"]
with 4 elements. I know i can use re.findall(r’"(.*?)"’, string) to find all values in quotation but it doesnt bring out true and false as an element
>Solution :
You can use r'"([^"]+)"|(true|false)':
import re
s = '"hi you, sir", true, false, "come, here"'
p = r'"([^"]+)"|(true|false)'
matches = re.findall(p, s)
print([m[0] if m[0] else m[1] for m in matches])
Prints
['hi you, sir', 'true', 'false', 'come, here']
If you don’t want the true and false as strings:
import re
def get_substr(s, p):
matches = re.findall(p, s)
res = []
for sub, tf in matches:
if sub:
res.append(sub)
if tf == 'true':
res.append(True)
if tf == 'false':
res.append(False)
return res
s = '"hi you, sir", true, false, "come, here"'
p = r'"([^"]+)"|(true|false)'
print(get_substr(s, p))
Prints
['hi you, sir', True, False, 'come, here']