簡體   English   中英

在python中使用正則表達式刪除特定字符之間的空格

[英]remove white space between specific characters using regex in python

我正在嘗試使用正則表達式按連續的'?'順序刪除空格。 和/或“!” 在一個字符串中。 一個例子是“那是什么?????????! 應該更改為“那是什么?????????? !!!?!”。 也就是說,我想將所有的'?'連接在一起 和'!' 中間沒有空格。 我當前的代碼效果不佳:

import re
s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
s = re.sub("\? +\?", "??", s)
s = re.sub("\? +\!", "?!", s)
s = re.sub("\! +\!", "!!", s)
s = re.sub("\! +\?", "!?", s)

產生“那是什么??? ???????! !?!',其中顯然沒有刪除一些空格。 我的代碼出了什么問題以及如何修改它?

您只是想壓縮標點符號周圍的空格,是嗎? 這樣的事情怎么樣:

>>> import re
>>> s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
>>> 
>>> re.sub('\s*([!?])\s*', r'\1', s)
'what is that??????????!!!?!'

如果您真的對為什么您的方法不起作用感興趣,則與正則表達式在字符串中的移動方式有關。 當您編寫re.sub("\\? +\\?", "??", s)並在您的字符串上運行它時,引擎將像這樣工作:

s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
# first match -----^^^
# internally, we have:
s = "what is that ??? ? ?? ??? ? ! ! ! ? !"
# restart scan here -^
# next match here ----^^^
# internally:
s = "what is that ??? ??? ??? ? ! ! ! ? !"
# restart scan here ---^
# next match here ------^^^

等等。 有幾種方法可以防止光標在檢查匹配項時前進(檢查正向提前)。

如果您想像@gddc所說的那樣並且句子模式是相同的,那么您可以嘗試以下方法:

string_="what is that ?? ? ? ?? ??? ? ! ! ! ? !"
string_1=[]
symbols=[]
string_1.append(string_[:string_.index('?')])
symbols.append(string_[string_.index('?'):])
string_1.append("".join(symbols[0].split()))
print("".join(string_1))

輸出:

what is that ??????????!!!?!

我的方法包括將字符串分成兩部分,然后使用正則表達式處理問題區域(刪除空格),然后將片段重新結合在一起。

import re s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !" splitted = s.split('that ') # don't forget to add back in 'that' later splitfirst = splitted[0] s = re.sub("\\s+", "", splitted[1]) finalstring = splitfirst+'that '+s print(finalstring) import re s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !" splitted = s.split('that ') # don't forget to add back in 'that' later splitfirst = splitted[0] s = re.sub("\\s+", "", splitted[1]) finalstring = splitfirst+'that '+s print(finalstring)輸出:

╭─jc@jc15 ~/.projects/tests ╰─$ python3 string-replace-question-marks.py what is that ??????????!!!?!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM