
September 8th, 2003, 04:51 PM
|
|
Contributing User
|
|
Join Date: Dec 2001
Location: Houston, TX
Posts: 383
Time spent in forums: 1 h 41 m 27 sec
Reputation Power: 7
|
|
Here's my massive regex for valid python math expressions. It's pretty well-tested:
Code:
# Comment for the regexes:
# Numbers:
# \.\d+ : a number like ".023"
# | : or
# \d+(\.\d*)? : numbers like "1.23" or "10." or "1"
# L? : ends in L or not
number = "(\.\d+|\d+(\.\d*)?)L?"
# Operands:
# \(* : some or no leading parentheses
# -? : negative (or not)
#
# number goes here
#
# \)* : some or no trailing parentheses
operand = "(\(*-?" + number + "\)*)"
# Operators:
# [ : one of these single char operators
# % : modulus
# + : addition
# - : subtraction
# / : division
# * : multiplication
# ]| : or
# \*\* : exponentiation
operator = "([%+-/*]|\*\*)"
# Total regex:
#
# ^ : starts with
# \s* : any amount of space, or none at all
#
# some operand
#
# \s* : some or no space after this
# ( : and any number of operator/operand pairs after this
#
# operator goes here
#
# \s* : some or no spacing
#
# operand goes here
#
# \s* : any amount of trailing space, or none at all
# )+ : one or more operator/number pairs
# $ : must end here as well
self.regex = "^\s*" + operand + "\s*(" + operator + "\s*" + operand + "\s*)+$"
---edit----
this was scraped from one of my projects' source files, so the "self.regex" is what you want, but obviously it's just a string that you'd have to re.compile() first to get a proper RE object.
|