How to replace all occurrences of regex as if applying replace repeatedly

Viewed 157

For example, I have text with a lot of product dimensions like "2x4" which I'd like to convert to "2 xby 4".

pattern = r"([0-9])\s*[xX\*]\s*([0-9])"

re.sub(pattern, r"\1 xby \2", "2x4")
'2 xby 4' # good

re.sub(pattern, r"\1 xby \2", "2x4x12")
'2 xby 4x12' # not good. need this to be '2 xby 4 xby 12'

One way of describing what I want to do is repeat the replacement until no more replacements can be made. For example, I can simply to the above replacement twice to get what I want

x = re.sub(pattern, r"\1 xby \2", "2x4x12")
x = re.sub(pattern, r"\1 xby \2", x)
'2 xby 4 xby 12'

But I assume there's a better way

3 Answers
Related