I want to remove these when they occur immeditately between two other characters, as in "a.2" or "1.2.3". But I don't want to remove them at the end of lines.
How do you want to handle multiple dots in a row? That is, do you expect
1..2
to map to
12
? Or to
1.2
? Or
1..2
?
How do you want to handle leading dots?
For the moment I’m assuming you want all dots removed except one at the end, in which case I first define a helper on
NSRegularExpression
[1]:
extension NSRegularExpression {
func stringByReplacingMatches(in string: String, withTemplate template: String) -> String {
let r = NSRange.init(string.startIndex..<string.endIndex, in: string)
return self.stringByReplacingMatches(in: string, options: [], range: r, withTemplate: template)
}
}
And then use it:
let re = try! NSRegularExpression(pattern: #"\.+(.)"#, options: [])
print(re.stringByReplacingMatches(in: "1.2", withTemplate: #"$1"#)) // 12
print(re.stringByReplacingMatches(in: "1..2", withTemplate: #"$1"#)) // 12
print(re.stringByReplacingMatches(in: "..1.2", withTemplate: #"$1"#)) // 12
print(re.stringByReplacingMatches(in: "1.2.", withTemplate: #"$1"#)) // 12.
print(re.stringByReplacingMatches(in: "1.2..", withTemplate: #"$1"#)) // 12.
print(re.stringByReplacingMatches(in: "...123...456...", withTemplate: #"$1"#)) // 123456.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
[1] Getting decent regular expression support into Swift continues to be an important goal. See this Swift Forums post for some background.