Re: regexp non-greedy matching bug?

Discussion in 'Python' started by John Hazen, Dec 4, 2005.

  1. John Hazen

    John Hazen Guest

    > [John Hazen]
    > > I want to match one or two instances of a pattern in a string.
    > >
    > > >>> s = 'foobarbazfoobar'
    > > >>> foofoo = re.compile(r'^(foo)(.*?)(foo)?(.*?)$')
    > > >>> foofoo.match(s).group(1)

    > > 'foo'
    > > >>> foofoo.match(s).group(3)
    > > >>>


    [Tim Peters]
    > Your problem isn't that
    >
    > (foo)?
    >
    > is not greedy (it is greedy), it's that your first
    >
    > (.*?)
    >
    > is not greedy. Remember that regexps also work left to right.


    Well, I had the same symptoms when that .* was greedy (it ate up the
    optional foo), which is why I went to non-greedy there.

    I guess my error was thinking that greedy trumped non-greedy, rather
    than left trumping right. (ie, in order for the (foo)? to be maximally
    greedy, the (.*?) has to be non-maximally non-greedy :)

    > Maybe what you're looking for is
    >
    > ^P(.*P)?.*$


    Yes. That works the way I wanted. ( ^(foo)(.*(foo))?.*$ )

    Thank you, both for the specific answer, and the general education.

    -John
    John Hazen, Dec 4, 2005
    #1
    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. kaeli
    Replies:
    3
    Views:
    11,309
  2. Sam Pointon

    regexp non-greedy matching bug?

    Sam Pointon, Dec 4, 2005, in forum: Python
    Replies:
    8
    Views:
    366
    Fredrik Lundh
    Dec 5, 2005
  3. Tim Peters

    Re: regexp non-greedy matching bug?

    Tim Peters, Dec 4, 2005, in forum: Python
    Replies:
    0
    Views:
    389
    Tim Peters
    Dec 4, 2005
  4. Dan Kelly

    Greedy and non greedy quantifiers

    Dan Kelly, Jan 17, 2008, in forum: Ruby
    Replies:
    4
    Views:
    143
    Robert Klemme
    Jan 19, 2008
  5. Matt Garrish

    greedy v. non-greedy matching

    Matt Garrish, Feb 16, 2004, in forum: Perl Misc
    Replies:
    4
    Views:
    162
    Matt Garrish
    Feb 16, 2004
Loading...

Share This Page