potentialwjy
potentialwjy

Reputation: 163

use findall() method to parse a simple math equations

how to use findall() method to parse a math equation?

for example, if I have an equation 8x >= 4 + 2y + 10z

here is my coding

import re
equations = '8x >= 4 + 2y + 10z'
regexparse = r'\w+|[+/*-]'
result = re.findall(regexparse, equations)
print(result)

the output is

['8x', '4', '+', '2y', '+', '10z']

instead, I expect this result:

[('','8','x','>='),('','4','',''),('+','2','y',''),('+','10','z','')]

Upvotes: 1

Views: 144

Answers (1)

blhsing
blhsing

Reputation: 106533

You should use 4 capture groups instead if you want re.findall to return a list of 4-tuples:

result = re.findall(r'(?=\S)([-+*/])?\s*(\d+)?\s*([a-z]+)?\s*([<>]?=)?', equations)

Given your sample input of equations = '8x >= 4 + 2y + 10z', result would become:

[('', '8', 'x', '>='), ('', '4', '', ''), ('+', '2', 'y', ''), ('+', '10', 'z', '')]

Upvotes: 1

Related Questions