Skip to content

Instantly share code, notes, and snippets.

@andru255
Last active November 19, 2018 15:05
Show Gist options
  • Save andru255/90805f798ac048843e36cf94a191fc08 to your computer and use it in GitHub Desktop.
Save andru255/90805f798ac048843e36cf94a191fc08 to your computer and use it in GitHub Desktop.
let patternEmail = "[\\w0-9\\.]+@[\\w.]+"
let raw = "1 2 foo@bar.com, jhon@haha.con"
let replaceWith = "xxx"
let text = raw.replace(pattern: patternEmail, with: replaceWith) // example
struct ReplacerPlusResult {
let textReplaced: String
var rangesApplied: [Range<String.Index>]
}
func replacerPlus(text: String, pattern: String, with: String, savedRanges: [Range<String.Index>] = []) -> ReplacerPlusResult? {
var ranges: [Range<String.Index>] = savedRanges ?? []
var mutableText = text
if let range = text.range(of: pattern, options: .regularExpression) {
mutableText = mutableText.replacingCharacters(in: range, with: with)
ranges.append(range)
return replacerPlus(text: mutableText, pattern: pattern, with: with, savedRanges: ranges)
}
return ReplacerPlusResult(textReplaced: mutableText, rangesApplied: ranges)
}
let result = replacerPlus(text: raw, pattern: patternEmail, with: replaceWith)
print(result?.textReplaced)
result?.rangesApplied.forEach({ print($0.lowerBound.encodedOffset) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment