2010-08-31 43 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...