How to match patterns like XX YY XX YY? (regex)

MRAB python at mrabarnett.plus.com
Sat Aug 7 14:20:46 EDT 2010


Peng Yu wrote:
> Hi,
> 
> Suppose that I have strings like the following
> 
> test(a b)a b
> test(xy uv)xy uv
> ...
> 
> I want to change them to
> 
> test(a)a test(b)b
> test(xy)xy test(uv)uv
> ...
> 
> 
> The problem is that I don't know how to capture pattern that repeat
> itself (like 'a' and 'xy' in the example). I could use 'test\((\w+)
> (\w+)\)(\w) (\w)', but it will capture something like 'test(a b)x y',
> which I don't want to.
> 
> I'm wondering if there is way to capture recurring patterns.
> 
Use backreferences (it's in the documentation):

     pattern = re.compile(r'test\((\w+) (\w+)\)\1 \2')



More information about the Python-list mailing list