Last active
February 29, 2024 16:16
-
-
Save robertmryan/7fc421b905d22be5063528e64676529a to your computer and use it in GitHub Desktop.
Swift 4 string extension to find all ranges of some substring
This file contains hidden or 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
extension StringProtocol where Index == String.Index { | |
func ranges<T: StringProtocol>(of substring: T, options: String.CompareOptions = [], locale: Locale? = nil) -> [Range<Index>] { | |
var ranges: [Range<Index>] = [] | |
while let result = range(of: substring, options: options, range: (ranges.last?.upperBound ?? startIndex)..<endIndex, locale: locale) { | |
ranges.append(result) | |
} | |
return ranges | |
} | |
} |
Or also,
let string = "Administrator or worker in office"
let pattern = Regex {
Anchor.wordBoundary
"or"
Anchor.wordBoundary
}.ignoresCase()
for match in string.matches(of: pattern) {
print(string[match.range])
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@kk143g – Personally, I would use the new Regex regular expressions, where
/…/
is a regex literal pattern, the pattern to be searched is between the/
delimiters, and where we use\b
to designate a “word boundary”:Or, if you needed to support old OS versions, you can use the extension shown above and use the
.regularExpression
option:For the sake of completeness, you could also use the NaturalLanguage framework, but that’s horrible overkill, IMHO.