Lochana Thenuwara Lochana Thenuwara - 26 days ago 7
Python Question

Return the values inside parenthesis in python

I'm trying to extract the values of following line inside the parenthesis.

line=(panel, wxID_EXIT, wxT("Quit"),wxPoint(20, 20))


expected answer is:

panel, wxID_EXIT, wxT("Quit"),wxPoint(20, 20)


but using the following

pattern=re.compile(r'\((.*?)\)')
match = re.search(pattern, line)


I only receive the following output.

(panel, wxID_EXIT, wxT("Quit")


Unfortunately my knowledge of regular expressions is very limited.Can someone help me to get the expected answer.

Answer

with that .*?, you turned off the greedy aspect of regular expression. Just remove the question mark to enable it again (this is default):

pattern=re.compile(r'\((.*)\)')

full test:

import re
line='(panel, wxID_EXIT, wxT("Quit"),wxPoint(20, 20))'
pattern=re.compile(r'\((.*)\)')
match = re.search(pattern, line)
print(match.group(1)=='panel, wxID_EXIT, wxT("Quit"),wxPoint(20, 20)')

True
Comments