正则表达式:匹配连续的标点符号并替换为第一个

Jen*_*ijn 3 python regex

I am trying to remove some predefined consecutive punctuation marks and replace them with the first. Thus:

  1. u.s., -> u.s.
  2. u.s. -> u.s.
  3. u.s.! -> u.s.
  4. hiiii!!!, -> hiiii!

I tried the following code:

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)
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 6

您只需要捕获第一个标点符号并匹配其余的:

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

正则表达式演示

请注意,-必须将放在字符类的末尾(或开始),以免创建范围(否则可以在字符类内部转义)。

详细资料

  • ([.,/#!$%^&*;:{}=_`~()-]) -使用您定义的标点符号捕获组
  • [.,/#!$%^&*;:{}=_`~()-]+ -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)
Run Code Online (Sandbox Code Playgroud)