Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use regex to get a list of all values in double quotes and true and false which dont have quotes?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading