我需要一種方法來刪除字符串中的所有空格,除非該空格在引號之間。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