Use regular expressions to replace overlapping subpatterns

python, regex

Solution

Use a lookahead assertion, `(?=...)`, so as not to eat up the second pattern:

In [33]: re.sub( r"([a-zA-Z0-9])\s+(?=[a-zA-Z0-9])" , r"\1*" , '3 a 5 b')
Out[33]: '3*a*5*b'

In [32]: re.sub( r"([a-zA-Z0-9])\s+(?=[a-zA-Z0-9])" , r"\1*" , "3 /a 5! b" )
Out[32]: '3 /a*5! b'

Problem

I have the following regular expression substitution: ``` input=re.sub( r"([a-zA-Z0-9])\s+([a-zA-Z0-9])" , r"\1*\2" , input ) ``` I use the regular expression on the string `"3 a 5 b"`. I get back `"3*a 5*b"`. I am thinking I should get back `"3*a*5*b"`. So somehow my regular expression substitutions are interfering with each other. What can I do to get the result I want, other than iterative runs of the regular expression?

Original source

Related problems