Equations with Regular Expressions
Aktay SW
aktay.sw at t-online.de
Wed Feb 27 11:11:38 EST 2002
Equations with Regular ExpressionsHi,
here is a piece of code that does the conversion:
*************************************
import re # import the regular expressions module
s='2x^3-2x^2+15' # set up the original string
s1=s # make a copy of the original string. it will be
modified for searching purposes
s2='' # create an empty resulting string
match=re.search('[0-9]x\^[0-9]+',s1) # search the string s1 for the first
time for: one digit followed by 'x^' followed by one or more digits
while match: # loop as long as there is a match
begin,end = match.span() # get beginning and ending character
positions of matching portion
if begin > 0: # if the matching portion does not
begin at the first character position you have to copy to the resulting
string
s2=s2+s1[:begin] # the characters from the beginning
of the string up to the first matching character
s2=s2+s1[begin:begin+1]+'*('+s1[begin+1:begin+2]+'**'+s1[begin+3:end]+')'
# paste the characters '*(', '**',
')' into the matching portion and add it to the resulting string
s1=s1[end:] # shorten string s1 by the
characters up the first character after the matching portion
match=re.search('[0-9]x\^[0-9]*',s1)# do the search again and go through
the loop if there was a match, else you're done with the loop
s2=s2+s1 # add any leftover characters to the resulting string
print s # print original string
print s2 # print conversion result
*************************************
I hope this helps you
regards
Ruhi Aktay
software
"Alves, Carlos Alberto - Coelce" <calves at coelce.com.br> schrieb im
Newsbeitrag news:mailman.1014805905.18241.python-list at python.org...
Hi everybody,
Could someone of you give me and example of how can I translate
'2x^3-2x^2+15' into '2*(x**3)-2*(x**2)+15' using regular expressions.
Carlos Alberto
COELCE/DPRON-Departamento de Projetos e Obras Norte
Fone: 677- 2228
e-mail: calves at coelce.com.br
\|||/
(o o)
--ooo0-(_)-0ooo--
More information about the Python-list
mailing list