Last active
November 19, 2018 15:05
-
-
Save andru255/90805f798ac048843e36cf94a191fc08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let patternEmail = "[\\w0-9\\.]+@[\\w.]+" | |
let raw = "1 2 [email protected], [email protected]" | |
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