簡體   English   中英

正則表達式:匹配連續的標點符號並替換為第一個

[英]Regex: match consecutive punctuation marks and replace by the first

我正在嘗試刪除一些預定義的連續標點符號,並將其替換為第一個。 從而:

  1. 我們->我們
  2. 我們->我們
  3. 我們! ->我們
  4. hiiii !!!,-> hiiii!

我嘗試了以下代碼:

import re
r = re.compile(r'([.,/#!$%^&*;:{}=-_`~()])*\1')
n = r.sub(r'\1', "ews by almalki : Tornado, flood deaths reach 18 in U.s., more storms ahead ")
print(n)

您只需要捕獲第一個標點符號並匹配其余的:

([.,/#!$%^&*;:{}=_`~()-])[.,/#!$%^&*;:{}=_`~()-]+

正則表達式演示

請注意, -必須放在字符類的末尾(或開始),以免創建范圍(否則可以在字符類內部轉義)。

詳細資料

  • ([.,/#!$%^&*;:{}=_`~()-]) -使用您定義的標點符號捕獲組
  • [.,/#!$%^&*;:{}=_`~()-]+ -1+個標點符號

Python演示

import re
r = re.compile(r'([.,/#!$%^&*;:{}=_`~()-])[.,/#!$%^&*;:{}=_`~()-]+')
n = r.sub(r'\1', "ews by almalki : Tornado, flood deaths reach 18 in U.s., more storms ahead ")
print(n)

暫無
暫無

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

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