What is a regular expression that will match any valid Python integer literal in a string? It should support all the extra stuff like o
and l
, but not match a float, or a variable with a number in it. I am using Python's re
, so any syntax supported by that is OK.
EDIT: Here's my motivation (as apparently that's quite important). I am trying to fix http://code.google.com/p/sympy/issues/detail?id=3182. What I want to do is create a hook for IPython that automatically converts int/int (like 1/2
) to Rational(int, int)
, (like Rational(1, 2)
. The reason is that otherwise it is impossible to make 1/2
be registered as a rational number, because it's Python type __div__
Python type. In SymPy, this can be quite annoying because things like x**(1/2)
will create x**0
(or x**0.5
with __future__
division or Python 3), when what you want is x**Rational(1, 2)
, an exact quantity.
My solution is to add a hook to IPython that automatically wraps all integer literals in the input with Integer (SymPy's custom integer class that gives Rational
on division). This will let me add an option to isympy
that will let SymPy act more like a traditional computer algebra system in this respect, for those who want it. I hope this explains why I need it to match any and all literals inside an arbitrary Python expression, which is why it needs to not match float literals and variables with numbers in their names.
Also, since everyone's so interested in what I tried, here it is: not much before I gave up (regular expressions are hard). I played with (?!\.)
to make it not catch the first part of float literals, but this didn't seem to work (I'd be curious if someone can tell me why, an example is re.sub(r"(\d*(?!\.))", r"S\(\1\)", "12.1")
).
EDIT 2: Since I plan to use this in conjunction with re.sub
, you might as well wrap the whole thing in parentheses in your answers so I can use \1
:)