mihsathe
mihsathe

Reputation: 9154

Python RegEx matching anomaly

I am trying to extract the LHS and RHS of a linear equation using the RegEx matching in Ptython.

exp="+1-3=x+2";
parts = re.search("(.*?)=(.*?)", exp);
left = parts.group(1);
right = parts.group(2);

although the value of left is correctly captured, the value of right is empty.

Is there something I am doing wrong? needless to say I am new to Python.

Thanks.

Upvotes: 2

Views: 105

Answers (1)

NPE
NPE

Reputation: 500257

Make the right-hand side greedy by removing the question mark:

parts = re.search("(.*?)=(.*)", exp);

Otherwise the matching stops right after the =.

Alternatively, use $ to anchor to the end of the string.

Finally, it is worth noting that you don't actually need a regex here:

left, _, right = exp.partition('=')

Upvotes: 4

Related Questions