Python 正则表达式必须去除引号之间的空格 [英] Python Regular expression must strip whitespace except between quotes
本文介绍了Python 正则表达式必须去除引号之间的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种方法来删除字符串中的所有空格,除非空格在引号之间.
I need a way to remove all whitespace from a string, except when that whitespace is between quotes.
result = re.sub('".*?"', "", content)
这将匹配引号之间的任何内容,但现在它需要忽略该匹配并为空格添加匹配..
This will match anything between quotes, but now it needs to ignore that match and add matches for whitespace..
推荐答案
我认为您无法使用单个正则表达式做到这一点.一种方法是在引号上拆分字符串,将空白剥离正则表达式应用于结果列表的每个其他项目,然后重新加入列表.
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."')
这篇关于Python 正则表达式必须去除引号之间的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文