简体   繁体   中英

How do I split on the space-separated math operators here?

I have a user calculator that accepts both numbers and user-defined variables. My plan is to split the statement on a space-delimited operator, eg ' + ':

import re
query = 'house-width + 3 - y ^ (5 * house length)'
query = re.findall('[+-/*//]|\d+|\D+', query)
print query  # ['house-width + ', '3', ' - y ^ (', '5', ' * house length)']

Expecting:
['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)']

Using re.split with capturing parentheses around the split pattern seems to work fairly effectively. As long as you have the capturing parens in the pattern the patterns you are splitting on are kept in the resulting list:

re.split(' ([+-/*^]|//) ', query)
Out[6]: ['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)']

(PS: I'm assuming from your original regex you want to catch // integer division operators, you can't do that with a single character class, so I've moved that outside the character class as a special case.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM