what is the elegant way to validate if string match regex?
I use the next regex to get gender, for example:
F = Female
M = Male
let idPassport = "G394968225MEX25012974M2807133<<<<<<06"
let regexGender = "[F|M]{1}[0-9]{7}"
let genderPassport = id passport.matchingStrings(regex: regexGender)
if genderPassport != nil{
print(genderPassport) // my output ["M2"]
}
I use this function to match string: https://stackoverflow.com/a/40040472/15324640
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
}
}
I only wat to get letter of the male : M or F