Reputation: 117
I would like to remove duplicated punctuations from a string using Swift 4.
e.g. "This is a test.... It is a good test!!!" to "This is a test. It is a good test!"
I cannot find any String/NSString functions to accomplish this. Any ideas?
Upvotes: 0
Views: 157
Reputation: 539795
This can be achieved with a regular expression string replacement:
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!
The ([:punct:])\1+
pattern matches any punctuation character, followed by
one or more occurences of the same character.
For each match, $1
in the replacement string is replaced by the contents of the
first capture group, which in our case is the punctuation character.
Upvotes: 1