Reputation: 91
I'm new to regex and would like to match (in my python-programm) mathematical expressions in a string using regex. Mathematical expressions are for me (now) single letters, numbers and expressions between square brackets. So e.g. for the given sentence (=string)
"Let f(a) in the variable a be 100 in the expression [[f(a)=a+1]]."
I'd like to get something like:
[f(a),a,100,f(a)=a+1]
I managed to get
1, the expression in the squared brackets using [[(.*?)]]
2, single letters and numbers using \b[0-9a-zA-Z]{1}\b and
3, numbers generally using \d+
, but not to get everything with one regular expression.
May someone help with an appropriate regex-module or would it be better to solve this problem in a pythonic way?
Upvotes: 2
Views: 1328
Reputation: 91
Finally I got it. Thanks to everyone! You made my day.
Thats my regular expression:
'(?<=[ ][[]{2}).*?(?=[]]{2}[ .!?])|\d+|\b[a-zA-Z0-9{+-}]*\([a-zA-Z0-9{+-}]*\)|\b[a-zA-Z]\b'
Upvotes: 0
Reputation: 1347
This will capture your mathematical expressions disregarding the number of brackets (?<=\[)[^\[]*?(?=\])
Check a demo here regex101
To get a list in python with your math expressions, you can use the following code:
p = re.compile('(?<=\[)[^\[]*?(?=\])')
p.findall('YOUR TEXT HERE')
Upvotes: 2