![](/img/trans.png)
[英]Use Regex to replace uppercase abbreviations with same letters but adding punctuation and space
[英]python regex inserting a space between punctuation and letters
我認為最好的方法是使用正則表達式,但我不知道該怎么做。 我試圖解析一個字符串,並在字母和標點之間放置一個空格。 我想把標點符號放在一起。 舉個例子,如果我有字符串
“是!!!”
我想結束
“是”,“!!!”。
如果我有字符串
!N00bs,
我想結束
“!!!”,“N00bs”
這可能嗎? 做這個的最好方式是什么? 現在我正在解析每個字母,這是一種愚蠢的方式。
謝謝您的幫助。
這樣的事情:
txt = re.sub( r'([a-zA-Z])([,.!])', r'\1 \2', '!!!this, .is, .a .test!!!' )
你可以切換另一個方向的順序
re.sub( r'([,.!])([a-zA-Z])', r'\1 \2', txt )
也許你也可以在一個正則表達式中使它工作
如果你只是想添加一個空格,可以使用替換?
x = x.replace('!',' ')
您可能必須使用更多替換來刪除標點符號和標點符號之間的空格。
我用的是:
(.+)\b(.+)
它既適用yes!!!
和!!!N00bs
說明:
The regular expression:
(?-imsx:(.+)\b(.+))
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
.+ any character except \n (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
.+ any character except \n (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.