Robust regex

Discussion in 'Python' started by Joseph L. Casale, Nov 19, 2012.

  1. Trying to robustly parse a string that will have key/value pairs separated
    by three pipes, where each additional key/value (if more than one exists)
    will be delineated by four more pipes.

    string = 'key_1|||value_1||||key_2|||value_2'
    regex = '((?:(?!\|\|\|).)+)(?:\|\|\|)((?:(?!\|\|\|).)+)(?:\|\|\|\|)?'

    I am not convinced this is the most effective or safest, any opinions would
    be greatly appreciated!

    jlc
     
    Joseph L. Casale, Nov 19, 2012
    #1
    1. Advertising

  2. Joseph L. Casale

    John Gordon Guest

    In <> "Joseph L. Casale" <> writes:

    > Trying to robustly parse a string that will have key/value pairs separated
    > by three pipes, where each additional key/value (if more than one exists)
    > will be delineated by four more pipes.
    > string = 'key_1|||value_1||||key_2|||value_2'
    > regex = '((?:(?!\|\|\|).)+)(?:\|\|\|)((?:(?!\|\|\|).)+)(?:\|\|\|\|)?'
    > I am not convinced this is the most effective or safest, any opinions would
    > be greatly appreciated!


    Regexes may be overkill here. A simple string split might be better:

    string = 'key_1|||value_1||||key_2|||value_2'
    pairs = string.split('||||')
    for pair in pairs:
    keyval = pair.split('|||')
    print '%s=%s' % (keyval[0], keyval[1])

    --
    John Gordon A is for Amy, who fell down the stairs
    B is for Basil, assaulted by bears
    -- Edward Gorey, "The Gashlycrumb Tinies"
     
    John Gordon, Nov 19, 2012
    #2
    1. Advertising

  3. > Regexes may be overkill here. A simple string split might be better:

    Yup, and much more robust as I was looking for.

    Thanks everyone!
    jlc
     
    Joseph L. Casale, Nov 19, 2012
    #3
    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. Martin Smith

    robust iterator implementation

    Martin Smith, Jan 24, 2005, in forum: C++
    Replies:
    4
    Views:
    4,141
    msalters
    Jan 25, 2005
  2. Replies:
    3
    Views:
    809
    Reedick, Andrew
    Jul 1, 2008
  3. Replies:
    3
    Views:
    169
    Paul Lalli
    Oct 27, 2005
  4. Chris Angelico

    Re: Robust regex

    Chris Angelico, Nov 19, 2012, in forum: Python
    Replies:
    0
    Views:
    154
    Chris Angelico
    Nov 19, 2012
  5. MRAB

    Re: Robust regex

    MRAB, Nov 19, 2012, in forum: Python
    Replies:
    0
    Views:
    150
Loading...

Share This Page