Python Regular expression must strip whitespace except between quotes

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

    I don't think you're going to be able to do that with a single regex. One way to do it is to split the string on quotes, apply the whitespace-stripping regex to every other item of the resulting list, and then re-join the list.

    import re
    
    def stripwhite(text):
        lst = text.split('"')
        for i, item in enumerate(lst):
            if not i % 2:
                lst[i] = re.sub("\s+", "", item)
        return '"'.join(lst)
    
    print stripwhite('This is a string with some "text in quotes."')
    

提交回复
热议问题