Looking for a regular expression to match tuple pairs within a list. Have been using the below regular expression
s = '[(aleakedteaserand, NN), (abehind, IN), (the, DT)]'
re.findall(r'\((.*,.*)\)',s)
but it still missing the end braces.
['aleakedteaserand, NN), (abehind, IN), (the, DT']
Expected output:
[(aleakedteaserand, NN), (abehind, IN), (the, DT)]
You didn't make the RegEx ungreedy. The solution is re.findall(r'\((.*?,.*?)\)',s)
.
Alternatives. First one uses a complement match often used as an alternative to non-greedy search where it is not available.
>>> re.findall(r'\(([^)]*)\)',s)
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']
>>> re.split('\), \(', s.strip('[()]'))
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']
No regex
>>> s.strip('[()]').split('), (')
['aleakedteaserand, NN', 'abehind, IN', 'the, DT']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With