Here's one for the regular expression aficionados. I have some strings containing full stops. 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.
I presume I'll have to use regular expressions to do this, and I think I know how to write one that will match those characters (although it looks so ugly I'm ashamed to post it here.) But I can't figure out how to use it to filter my strings. Suggestions would be welcome.
The responses from Claude and Quinn inspired me to come up with this code (from a playground):
var testString = "I want to get rid 1.2.3 of inline citations. But I don't want 1.2.4 to get rid of full stops."
let pattern = #"\.[^\s]"# // Matches . before non-whitespace characters.
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let mString = NSMutableString(string: testString)
regex.replaceMatches(in: mString, options: [], range: NSMakeRange(0, mString.length), withTemplate: "")
testString = String(mString)
testString = testString.filter {CharacterSet.decimalDigits.inverted.contains($0.unicodeScalars.first!)}
testString = testString.replacingOccurrences(of: " ", with: " ")
This gives me what I want:
I want to get rid of inline citations. But I don't want to get rid of full stops.
Having to switch between String and NSMutableString is a bit of a nuisance, but perhaps that won't be necessary in future versions of Swift.
I'll wait to see if you guys have any improvements before marking this as correct!