Re: emulating an and operator in regular expressions

Discussion in 'Python' started by Craig Ringer, Jan 3, 2005.

  1. Craig Ringer

    Craig Ringer Guest

    On Mon, 2005-01-03 at 08:52, Ross La Haye wrote:
    > How can an and operator be emulated in regular expressions in Python?
    > Specifically, I want to return a match on a string if and only if 2 or more
    > substrings all appear in the string. For example, for a string s = 'Jones
    > John' and substrings sg0 = 'Jones' and sg1 = 'John', I want to return a
    > match, but for substrings sg0 = 'Jones' and sg2 = 'Frank' I do not want to
    > return a match. Because the expression 'A and B' is logically equivalent to
    > 'not (not A or not B)' I thought I could try something along those lines,
    > but can't crack it.


    My first thought would be to express your 'A and B' regex as:

    (A.*B)|(B.*A)

    with whatever padding, etc, is necessary. You can even substitute in the
    sub-regex for A and B to avoid writing them out twice.

    --
    Craig Ringer

    --
    Craig Ringer
     
    Craig Ringer, Jan 3, 2005
    #1
    1. Advertising

  2. Craig Ringer

    Andrew Dalke Guest

    Craig Ringer wrote:
    > My first thought would be to express your 'A and B' regex as:
    >
    > (A.*B)|(B.*A)
    >
    > with whatever padding, etc, is necessary. You can even substitute in the
    > sub-regex for A and B to avoid writing them out twice.


    That won't work because of overlaps. Consider

    barkeep

    with a search for A='bark' and B='keep'.

    Neither A.*B nor B.*A will match because the 'k' needs to
    be in both A and B.

    The OP asked for words, so consecutive letters separated
    by non-letters or end of string. With that restriction
    this solution will work.

    Another possibility is to use positive assertions, as in
    (?=A)(?=.*B)|(?=B)(?=.*A)

    The best solution is to do a string.find and not worry about
    implementing this as a regexp.

    Andrew
     
    Andrew Dalke, Jan 3, 2005
    #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. Jay Douglas
    Replies:
    0
    Views:
    635
    Jay Douglas
    Aug 15, 2003
  2. Jason
    Replies:
    4
    Views:
    1,682
    Jason
    May 7, 2007
  3. Sean Davis

    emulating read and readline methods

    Sean Davis, Sep 10, 2008, in forum: Python
    Replies:
    6
    Views:
    434
  4. Eduardo Tongson
    Replies:
    3
    Views:
    208
    Eduardo Tongson
    Dec 13, 2007
  5. Noman Shapiro
    Replies:
    0
    Views:
    255
    Noman Shapiro
    Jul 17, 2013
Loading...

Share This Page