Python Regular expression must strip whitespace except between quotes

后端 未结 5 1203
一个人的身影
一个人的身影 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 18:58

    Here is a one-liner version, based on @kindall's idea - yet it does not use regex at all! First split on ", then split() every other item and re-join them, that takes care of whitespaces:

    stripWS = lambda txt:'"'.join( it if i%2 else ''.join(it.split())
        for i,it in enumerate(txt.split('"'))  )
    

    Usage example:

    >>> stripWS('This is a string with some "text in quotes."')
    'Thisisastringwithsome"text in quotes."'
    

提交回复
热议问题