2010-08-31 95 views
4

我需要一种方法来删除字符串中的所有空格,除非该空格在引号之间。Python正则表达式必须去除除引号之外的空格

result = re.sub('".*?"', "", content) 

这将匹配报价之间的任何东西,但现在它需要忽略那场比赛,并添加匹配的空格..

+3

的问题是不明确的。当你有''a“b”'作为输入时它应该做什么? – NullUserException 2010-08-31 13:50:18

+0

内容将永远不会包含嵌套引号,所以这不是问题 – Oli 2010-08-31 13:56:28

+0

但是,正则表达式不适用于此任务。 – NullUserException 2010-08-31 14:02:54

回答

5

我不认为你将能够做到这一点与一个单一的正则表达式。一种方法是将引号拆分为字符串,将空白剥离正则表达式应用于结果列表的每个其他项目,然后重新加入列表。

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."') 
+0

+ 1的工作解决方案! – jathanism 2010-08-31 14:34:49

+0

我相信,有人会很快将其替换为单行列表理解。:-) – kindall 2010-08-31 14:45:08

+0

哈哈哈 - 我实际上在发帖之后错过了单线的评论。尽管如此,我确实依靠你的想法。 ++ – 2010-08-31 23:59:10

4

可以使用shlex.split的报价感知分割,并加入结果使用“”.join。例如。

print " ".join(shlex.split('Hello "world  this is" a test')) 
+0

您的示例给了我'你好世界这是一个测试'而不是'你好'世界这是'atest' – Oli 2010-08-31 14:07:43

+0

@Oli:你可以使用'map(pipes.quote,shlex.split(..))'在必要时添加引号 – jfs 2013-01-27 16:18:23

0

这里的小长版与检查没有对报价。只有(“)(”适应例如例如开始,结束=)开始和结束串的一个类型交易的

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 
5

这里是一个班轮版本的基础上,@ 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."' 
+0

我很遗憾,我只有一个满意的解决方案。 – kindall 2010-08-31 23:52:24

1

奥利,复活这个问题,因为它有一个那是没有提到简单的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) 

参考

  1. How to match pattern except in situations s1, s2, s3
  2. How to match a pattern unless...