Equations with Regular Expressions

Harvey Thomas hst at empolis.co.uk
Wed Feb 27 11:47:31 EST 2002


try the following (extended to allow for x^n)

import re

def dosub(mg):
    if mg.group(1):
        return '%s*(%s**%s)' % (mg.group(1), mg.group(2), mg.group(3))
    else:
        return '%s**%s' % (mg.group(2), mg.group(3))

regex = re.compile('(\d*)([a-zA-Z])\^(\d+)')
print regex.sub(dosub, '2x^3-2x^2+15-x^4*6')


-----Original Message-----
From: Alves, Carlos Alberto - Coelce [mailto:calves at coelce.com.br]
Sent: 27 February 2002 10:33
To: python-list at python.org
Subject: Equations with Regular Expressions


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-- 

_____________________________________________________________________
This message has been checked for all known viruses by Star Internet
delivered through the MessageLabs Virus Scanning Service. For further
information visit http://www.star.net.uk/stats.asp or alternatively call
Star Internet for details on the Virus Scanning Service.

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.




More information about the Python-list mailing list