Python Regular expression must strip whitespace except between quotes

后端 未结 5 1264
一个人的身影
一个人的身影 2020-12-11 18:43

I need a way to remove all whitespace from a string, except when that whitespace is between quotes.

result = re.sub(\'\".*?\"\', \"\", content)
5条回答
  •  一个人的身影
    2020-12-11 19:10

    You can use shlex.split for a quotation-aware split, and join the result using " ".join. E.g.

    print " ".join(shlex.split('Hello "world     this    is" a    test'))
    

提交回复
热议问题