[英]Remove space delimited single characters
我有這樣的文字:
the quick brown fox 狐狸 m i c r o s o f t マ イ ク ロ ソ フ ト jumps over the lazy dog 跳過懶狗 best wishes : John Doe
什么是可以刪除單個字符的好正則表達式(對於 python),以便 output 看起來像這樣:
the quick brown fox 狐狸 jumps over the lazy dog 跳過懶狗 best wishes John Doe
我嘗試了\s{1}\S{1}\s{1}\S{1}
一些組合,但它們最終不可避免地刪除了比我需要的更多的字母。
非正則表達式版本可能如下所示:
source_string = r"this is a string I created"
modified_string =' '.join([x for x in source_string.split() if len(x)>1])
print(modified_string)
您可以將以下內容替換為空字符串:
(?<!\S)\S(?!\S).?
匹配一個兩邊都沒有非空格(即被空格包圍)的非空格,加上后面的字符(如果有的話)。
我使用否定環視的原因是因為它巧妙地處理了字符串大小寫的開始/結束。 我們匹配\S
之后的額外字符以刪除空格。
請使用正則表達式嘗試以下代碼,我在其中尋找至少兩次可以消除單個字符問題的字符。
s='the quick brown fox 狐狸 m i c r o s o f t マ イ ク ロ ソ フ ト jumps over the lazy dog 跳過懶狗 best wishes : John Doe'
output = re.findall('\w{2,}', s)
output = ' '.join([x for x in output])
print(output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.