kinda noob here. So, please forgive me.
I'd like to pars a 4th degree string equations to its components and I wonder what kind of Regex will I need. Let's say the equation are :
"x^4 5x^3 - 2x - 18"
I'd like to turn this into [x^4, 5x^3, -2x, -18]
Thank you
CodePudding user response:
Not sure this needs a regular expression. It's a simple parsing problem.
expr = "x^4 5x^3 - 2x - 18"
token = ''
tokens = []
for c in expr:
if c == ' ':
tokens.append(token)
token = ''
elif c == '-':
tokens.append(token)
token = '-'
elif c != ' ':
token = c
tokens.append(token)
print(tokens)
Output:
['x^4', '5x^3', '-2x', '-18']
CodePudding user response:
Here is one I came up with for your case, if it as simple as that then this would work fine, but if we need to start getting parenthesis involved that is a whole new pickle :D. I had trouble getting the last value for some reason so I just put an | in there.
(?<=\s|\b|[\-\ ])((\d )|(\d*(\w\^*\d*)))(?=\s|\b|[\-\ ])
where ((\d )|(\d*(\w\^*\d*)))
is the central piece that actually captures your groups and the lookbehind and lookahead set the edges.
You can play around with it at https://www.regexpal.com/