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

Discussion in 'Python' started by Peng Yu, Aug 7, 2010.

  1. Peng Yu

    Peng Yu Guest

    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
     
    Peng Yu, Aug 7, 2010
    #1
    1. Advertising

  2. Peng Yu

    Alex Willmer Guest

    On Aug 7, 4:48 pm, Peng Yu <> 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')
    >>>
     
    Alex Willmer, Aug 7, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. hiwa
    Replies:
    0
    Views:
    640
  2. thorsten
    Replies:
    1
    Views:
    458
  3. crichmon
    Replies:
    4
    Views:
    488
    Mabden
    Jul 7, 2004
  4. Replies:
    3
    Views:
    773
    Reedick, Andrew
    Jul 1, 2008
  5. FangQ

    match 2D patterns with perl

    FangQ, Aug 9, 2006, in forum: Perl Misc
    Replies:
    5
    Views:
    120
    Ralf Muschall
    Aug 14, 2006
Loading...

Share This Page