The goal is what to the following String:
expresión = "(L1^10)∪L1∪L2^-1"
I should get the following result:
['(','L1','^10',')','∪','L1','∪','L2','^-1']
The condition for deciding the resulting pieces is that the numbers following a capital "L" must not be separated, and the exponents "^Number" must not be separated
I am not finding a way to obtain that result, what is the best alternative to achieve it?
It is difficult to find a pattern (regular expression) usable by
re.split()
so that it divides by all the points where that pattern appears.It's also hard to find a regular expression that will generate the groups you need, since we don't even know how many groups there can be right off the bat.
But I have come up with a relatively simple solution:
r"L\d+|\^-?\d+"
The following code implements that idea:
The result (list
trozos
) is:By helping you with the
findall()
modulus functionre
, and with a pattern quite similar to abulafia's, you can get the output you want.The pattern would be the following:
Which, analyzing it, does:
L\d+
: A letter L followed by one or more digitseither
\^\-?\d+
: The ^ symbol, followed by (optionally) a minus sign and one or more numberseither
.
: Anything else.Here it is important to know the importance of the precedence of the elements of the pattern. The
.
last one must be placed so that it only matches the elements that do not meet the two preceding criteria.Thus, we can have the following fairly simple code:
Where
resultado
will be a list containing: