我想更改以单个字符替换文本中所有重复的(2+)标点字符:

text = "-alham sedang bermain-main dan makan-makan???? @@alhamsya"

result = "-alham sedang bermain-main dan makan-makan? @alhamsya"


这是我的代码(和here it is on regex reference tester):

def duplicate_punctuation(text):
     pattern_regex = "([?@])\\1+"
     regex_req = re.sub(pattern_regex, "\\1", text)
     return regex_req

最佳答案

您的表情似乎运作良好:

import re

regex = r"([?@])\1+"

test_str = "-alham sedang bermain-main dan makan-makan???? @@alhamsya"
subst = "\\1"

result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

关于python - 如何使用正则表达式将所有重复的标点符号替换为单个标点符号?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56961401/

10-12 18:54