Created
August 19, 2021 14:40
-
-
Save carlynorama/4307eed19393dd91d738c2a56d892127 to your computer and use it in GitHub Desktop.
Easier regex with strings Swift
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
extension String | |
{ | |
func regexResultStrings(pattern:String) -> [String] | |
{ | |
if let regex = try? NSRegularExpression(pattern: pattern, options: []) | |
{ | |
let string = self as NSString | |
return regex.matches(in: self, options: [], range: NSRange(location: 0, length: string.length)).map { | |
string.substring(with: $0.range) | |
} | |
} | |
return [] | |
} | |
func regexResultComponentStrings(pattern:String) -> [[String]] { | |
if let regex = try? NSRegularExpression(pattern: pattern) { | |
let string = self | |
return regex.matches( | |
in: string, | |
range: NSRange(string.startIndex..., in: string) | |
).map { match in | |
return (0..<match.numberOfRanges).map { | |
let rangeBounds = match.range(at: $0) | |
guard let range = Range(rangeBounds, in: string) else { | |
return "" | |
} | |
return String(string[range]) | |
} | |
} | |
} | |
return [] | |
} | |
func contains(pattern:String) -> Bool { | |
let result = self.range( | |
of: pattern, | |
options: .regularExpression | |
) | |
return result != nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment