我需要一种方法来删除字符串中的所有空格,除非该空格在引号之间。Python正则表达式必须去除除引号之外的空格
result = re.sub('".*?"', "", content)
这将匹配报价之间的任何东西,但现在它需要忽略那场比赛,并添加匹配的空格..
我需要一种方法来删除字符串中的所有空格,除非该空格在引号之间。Python正则表达式必须去除除引号之外的空格
result = re.sub('".*?"', "", content)
这将匹配报价之间的任何东西,但现在它需要忽略那场比赛,并添加匹配的空格..
我不认为你将能够做到这一点与一个单一的正则表达式。一种方法是将引号拆分为字符串,将空白剥离正则表达式应用于结果列表的每个其他项目,然后重新加入列表。
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."')
这里的小长版与检查没有对报价。只有(“)(”适应例如例如开始,结束=)开始和结束串的一个类型交易的
start, end = '"', '"'
for test in ('Hello "world this is" atest',
'This is a string with some " text inside in quotes."',
'This is without quote.',
'This is sentence with bad "quote'):
result = ''
while start in test :
clean, _, test = test.partition(start)
clean = clean.replace(' ','') + start
inside, tag, test = test.partition(end)
if not tag:
raise SyntaxError, 'Missing end quote %s' % end
else:
clean += inside + tag # inside not removing of white space
result += clean
result += test.replace(' ','')
print result
这里是一个班轮版本的基础上,@ kindall的想法 - 但它不完全可以使用正则表达式!上”,然后分割第一分割()每其他项目,并重新加入他们,照顾空格的:
stripWS = lambda txt:'"'.join(it if i%2 else ''.join(it.split())
for i,it in enumerate(txt.split('"')) )
用例:
>>> stripWS('This is a string with some "text in quotes."')
'Thisisastringwithsome"text in quotes."'
我很遗憾,我只有一个满意的解决方案。 – kindall 2010-08-31 23:52:24
奥利,复活这个问题,因为它有一个那是没有提到简单的regex解决方案(发现你的问题而做一些研究的regex bounty quest。)
这里的小正则表达式:
"[^"]*"|(\s+)
变更的左侧匹配完成"quoted strings"
。我们将忽略这些匹配。右侧与第1组匹配并捕获空间,并且我们知道它们是正确的空间,因为它们与左侧的表达式不匹配。
下面是工作的代码(和online demo):
import re
subject = 'Remove Spaces Here "But Not Here" Thank You'
regex = re.compile(r'"[^"]*"|(\s+)')
def myreplacement(m):
if m.group(1):
return ""
else:
return m.group(0)
replaced = regex.sub(myreplacement, subject)
print(replaced)
参考
的问题是不明确的。当你有''a“b”'作为输入时它应该做什么? – NullUserException 2010-08-31 13:50:18
内容将永远不会包含嵌套引号,所以这不是问题 – Oli 2010-08-31 13:56:28
但是,正则表达式不适用于此任务。 – NullUserException 2010-08-31 14:02:54