Home > Back-end >  Validate if string match with regex
Validate if string match with regex

Time:11-11

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

CodePudding user response:

To get the M letter use

import Foundation

let idPassport = "G394968225MEX25012974M2807133<<<<<<06"
let regexGender = "[FM](?=[0-9]{7})"
var genderPassport=""
if let rng = idPassport.range(of: regexGender, options: .regularExpression) {
    genderPassport=String(idPassport[rng])
}
print(genderPassport)
// => M

Here, [FM](?=[0-9]{7}) matches F or M that are followed with any seven digits.

  • Related