0

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?

danlai
  • 99
  • 1
  • 5

1 Answers1

1

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382