Python Regex - Create explicit multiplication -
i want replace implicit multiplication in strings (such "ax") explicit multiplication (such "ax"). have of done, except wanted add replace such "a(x+1)" "a(x+1)".
so far, pattern is:
pattern = re.compile("([0-9]+|[a-z\)])([a-z\(])", re.ignorecase) i using pattern.sub actual replacing:
s = "rx(3x)r" print pattern.sub('\\1*\\2', s) however, not replace "a(" "a*(". how can fix this?
you can use lookahead assertion:
>>> pattern = re.compile("([0-9]+|[a-z\)])(?=[a-z\(])", re.ignorecase) >>> s = "rx(3x)r" >>> print pattern.sub('\\1*', s) r*x*(3*x)*r the problem regex pattern matches rx , inserts *. however, can't match x again insert * between x(. if use lookahead, don't consume x available matched part of expression. of course, here sub pattern needs change since there no second group.
Comments
Post a Comment