Created
August 4, 2021 15:32
-
-
Save fbongcam/58241576288448f289b11c7472b89daf to your computer and use it in GitHub Desktop.
regexMatch
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
/* | |
@author Filip Bongcam | |
--------------------- | |
Compare string against custom regex | |
@param string to analyze | |
@param regex to compare against | |
@param if comparision should be case sensitive or not | |
@return true or false | |
*/ | |
static func regexMatch(string: String, regexPattern: String, caseSensitive: Bool = false) -> Bool | |
{ | |
let string = string as NSString | |
// Regex object | |
var regex = NSRegularExpression() | |
if caseSensitive == true | |
{ | |
do | |
{ | |
regex = try NSRegularExpression(pattern: regexPattern) | |
} catch { | |
print("Invalid regex pattern.") | |
return false | |
} | |
} | |
else | |
{ | |
do | |
{ | |
regex = try NSRegularExpression(pattern: regexPattern, options: .caseInsensitive) | |
} catch { | |
print("Invalid regex pattern.") | |
return false | |
} | |
} | |
let match = regex.firstMatch(in: string as String, options: [], range: NSRange(location: 0, length: string.length)).map { string.substring(with: $0.range) | |
} | |
if match != "" | |
{ | |
return true | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment