Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > How to match patterns like XX YY XX YY? (regex)

Reply
Thread Tools

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

 
 
Peng Yu
Guest
Posts: n/a
 
      08-07-2010
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.


--
Regards,
Peng
 
Reply With Quote
 
 
 
 
Alex Willmer
Guest
Posts: n/a
 
      08-07-2010
On Aug 7, 4:48*pm, Peng Yu <(E-Mail Removed)> wrote:
> 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.


Back references can deal with repetition.

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.match(r'test\((\w+) (\w+)\)\1 \2', 'test(xy uv)xy uv').groups()

('xy', 'uv')
>>> re.match(r'test\((\w+) (\w+)\)\1 \2', 'test(a b)x y')
>>>

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
match 2D patterns with perl FangQ Perl Misc 5 08-14-2006 04:22 PM
Regex: string match against mutiple patterns thorsten Java 1 03-10-2005 07:07 PM
Patterns for outlook like ASP.NET application? Julia ASP .Net 1 02-16-2005 02:31 AM
where to find good patterns and sources of patterns (was Re: singletons) crichmon C++ 4 07-07-2004 10:02 PM



Advertisments