is there any lib can split string in this way?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Leo Jay

    #1

    is there any lib can split string in this way?

    I want to split a string like this:
    'abc def "this is a test" ok'
    into:
    ['abc', 'def', 'this is a test', 'ok']

    is there any lib meet my need?

    thanks

    --
    Best Regards,
    Leo Jay
  • Bengt Richter

    #2
    Re: is there any lib can split string in this way?

    On Mon, 9 Jan 2006 13:59:44 +0800, Leo Jay <python.leojay@ gmail.com> wrote:
    [color=blue]
    >I want to split a string like this:
    >'abc def "this is a test" ok'
    >into:
    >['abc', 'def', 'this is a test', 'ok']
    >
    >is there any lib meet my need?
    >[/color]
    Narrowly interpreting your requirements (only quotes are with
    double quotes (never containing escaped same) and strip quotes off)
    and tested only as you see ;-)
    [color=blue][color=green][color=darkred]
    >>> import re
    >>> rx = re.compile(r'"([^"]*)"|(\w+)')
    >>> s = 'abc def "this is a test" ok'
    >>> [a or b for a,b in rx.findall(s)][/color][/color][/color]
    ['abc', 'def', 'this is a test', 'ok']

    Regards,
    Bengt Richter

    Comment

    • bonono@gmail.com

      #3
      Re: is there any lib can split string in this way?

      This has been asked not long ago. the shlex module as well as csv
      module both should be able to handle it. for this simple case
      shlex.split() seems to be the easiest.

      Leo Jay wrote:[color=blue]
      > I want to split a string like this:
      > 'abc def "this is a test" ok'
      > into:
      > ['abc', 'def', 'this is a test', 'ok']
      >
      > is there any lib meet my need?
      >
      > thanks
      >
      > --
      > Best Regards,
      > Leo Jay[/color]

      Comment

      Working...