Split a string by spaces — preserving quoted substrings — in Python

后端 未结 16 860
心在旅途
心在旅途 2020-11-22 15:05

I have a string which is like this:

this is \"a test\"

I\'m trying to write something in Python to split it up by space while ignoring spac

16条回答
  •  余生分开走
    2020-11-22 15:38

    Hmm, can't seem to find the "Reply" button... anyway, this answer is based on the approach by Kate, but correctly splits strings with substrings containing escaped quotes and also removes the start and end quotes of the substrings:

      [i.strip('"').strip("'") for i in re.split(r'(\s+|(?

    This works on strings like 'This is " a \\\"test\\\"\\\'s substring"' (the insane markup is unfortunately necessary to keep Python from removing the escapes).

    If the resulting escapes in the strings in the returned list are not wanted, you can use this slightly altered version of the function:

    [i.strip('"').strip("'").decode('string_escape') for i in re.split(r'(\s+|(?

提交回复
热议问题