2

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

1
  • 1
    Looks like you get [["M2807133"]]. What if you just use let regexGender = "[FM](?=[0-9]{7})"? Commented Nov 11, 2021 at 0:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.