I was working of a mathematical formula ,I need to split operands for the processing,
I was using re.split('\ |\-|\*|\/', Formula)
function in python to split the formula into operands.
But I have one notation wa(A,[-126,5-123,-120,-117,-114,-111,-108,-105,-102,-99,-96,-93,-90,-87,-84,-81,-78])-B-C-D which I couldn't split using the above regex as its splits the number in the list too(its taking - before 126 also for spliting)
Is there any way we can using regex and split into [wa(A,[-126,-123,-120,-117,-114,-111,-108,-105,-102,-99,-96,-93,-90,-87,-84,-81,-78]),B,C,D] , or I need to loop through the expression and write the logic?
CodePudding user response:
You might use an alternation to match either word characters followed by an opening till closing parenthesis, or match any char except a hyphen.
\w \([^()] \)|[^\s /*-]
See a regex demo and a Python demo.
import re
pattern = r"\w \([^()] \)|[^\s /*-] "
s = "wa(A,[-126,5-123,-120,-117,-114,-111,-108,-105,-102,-99,-96,-93,-90,-87,-84,-81,-78])-B-C-D"
print(re.findall(pattern, s))
Output
['wa(A,[-126,5-123,-120,-117,-114,-111,-108,-105,-102,-99,-96,-93,-90,-87,-84,-81,-78])', 'B', 'C', 'D']