我有一个用例,我想用一个空格替换多个空格,除非它们出现在引号内。例如如果多个空格不在引号之间出现,请用单个空格替换多个空格?
原始
this is the first a b c
this is the second "a b c"
this is the first a b c
this is the second "a b c"
后,我相信一个正则表达式应该能够做的伎俩,但我没有与他们太多的经验。下面是一些代码,我已经有
import re
str = 'this is the second "a b c"'
# Replace all multiple spaces with single space
print re.sub('\s\s+', '\s', str)
# Doesn't work, but something like this
print re.sub('[\"]^.*\s\s+.*[\"]^, '\s', str)
我明白了为什么我的第二个以上不工作,所以只是想一些替代方法。如果可能的话,你能解释一下你的regex解决方案的一些部分吗?由于
你有这样的事情:'asdasdasd“asdasdasd ____ asdajskd”'('_'代表空格)。你只用空间工作,还是你也想处理新的行? – nhahtdh 2013-03-20 17:06:29
是的。里面的引号可以是任何东西,它应该被忽略 – Shane 2013-03-20 17:09:39
'里面的引号可以是任何东西'它可以包含新行吗? – nhahtdh 2013-03-20 17:11:59