gpt4 book ai didi

Swift - 删除重复的标点符号

转载 作者:行者123 更新时间:2023-11-30 11:23:55 40 4
gpt4 key购买 nike

我想使用 Swift 4 删除字符串中重复的标点符号。

e.g. "This is a test.... It is a good test!!!" to "This is a test. It is a good test!"

我找不到任何 String/NSString 函数来完成此操作。有什么想法吗?

最佳答案

这可以通过正则表达式字符串替换来实现:

let string = "This is a test.... It is a good test!!!"
let fixed = string.replacingOccurrences(of: "([:punct:])\\1+", with: "$1",
options: .regularExpression)
print(fixed) // This is a test. It is a good test!

([:punct:])\1+ 模式匹配任何标点字符,后跟同一字符出现一次或多次。

对于每个匹配,替换字符串中的 $1 被替换为第一个捕获组,在我们的例子中是标点符号。

关于Swift - 删除重复的标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50965041/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com