Suppose I have the following expression:
"1+3x+52-9-45x+x"
my goal is to extract all the constants: [1,+52,-9]
I have tried using Python:
re.findall("[+-]?\d+","1+3x+52-9-45x+x")
Result is:
['1', '+3', '+52', '-9', '-45']
which are not correct because the coefficents of x are also extracted.
I also tried:
re.findall("[+-]?\d+[+-]?","1+3x+52-9-45x+x")
But still not working.
Try this Regex:
(?:[+-])?\b\d+\b
OR
(?:[+-])?\d+(?=[\s+-]|$)
Explanation(for the 1st Regex):
(?:[+-])
Matching Either a +
or a -
(Add more operators if you want)?
Making +
or -
optional\b\d+\b
matching 1 or more digits between 2 non-words(so it will not include the coefficients)Explanation(for the 2nd Regex):
(?:[+-])
Matching Either a +
or a -
(Add more operators if you want)?
Making +
or -
optional\d+(?=[+-])
matching 1 or more digits(greedy) immediately followed by a +
or -
or a space or If it is the end of line. You can add more operators if you want.Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments