Skip to content

Instantly share code, notes, and snippets.

@fbongcam
Created August 4, 2021 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fbongcam/58241576288448f289b11c7472b89daf to your computer and use it in GitHub Desktop.
Save fbongcam/58241576288448f289b11c7472b89daf to your computer and use it in GitHub Desktop.
regexMatch
/*
@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