3

i tried all possibilities in stack-overflow (link1, link2) answers no use for me.

I am using following Regex to validate a first name. In online case (OnlineRegex) it is working fine but when i implemented in mobile it is not working.

Please help me

func isValidName() -> Bool {
    let RegEx = "^[a-zA-Z]+(([\\'\\,\\.\\-\\ ][a-zA-Z ])?[a-zA-Z]*)*$"
    let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
    return Test.evaluate(with: self)
}

i am calling above function as

let str = "John D'Largy"
        if str.isValidName(){
            print("Valid")
        }else{ print("Not valid")}

Output : "Valid"

Same function i am calling to validate my first text feild i am getting "Not valid"

if firstNameTxt.text.isValidName(){
            print("Valid")
        }else{ print("Not valid")}

i entered same text in mobile keyword

OutPut: "Not valid"

Did i missing something? or Should i have to change regex value?. Any suggestions.

Thanks in Advance.

Bhavesh Nayi
  • 3,626
  • 1
  • 27
  • 42
chandra1234
  • 357
  • 6
  • 15

2 Answers2

2

You may use

(?:[a-zA-Z]+(?:['‘’,.\\s-]?[a-zA-Z]+)*)?

The code you have already requires the full string match and you need no explicit anchors like ^ / \A and $ / \z.

Also, since the single quotation marks are automatically converted to curly quotes, you should either add them to the regex or turn off the behavior.

One of the most important things about thi regex is that it should be able to match partially correct string, thus all of the parts are optional (i.e. they can match 0 chars). It is wrapped with an optional non-capturing group ((?:...)?) that matches 1 or 0 occurrences.

Regex details

  • [a-zA-Z]+ - 1 or more letters
  • (?: - start of the inner non-capturing group:
    • ['‘’,.\\s-]? - 1 or 0 whitespaces, single quotes, hyphens
    • [a-zA-Z]+ - 1+ letters
  • )* - 0 or more repetitions.

Note: to match any Unbicode letter, use \\p{L} instead of [a-zA-Z].

Graph:

enter image description here

Bhavesh Nayi
  • 3,626
  • 1
  • 27
  • 42
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

See, I tried your code in the playground and changed the syntax a bit but not the logic

enter image description here

Below is the code snippet, try running that in your playground

    func isValidName(str: String) -> Bool {
       let RegEx = "^[a-zA-Z]+(([\\'\\,\\.\\-\\ ][a-zA-Z ])?[a-zA-Z]*)*$"
       let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
       return Test.evaluate(with: str)
    }

    func check(){
       let str = "John D'Largy"

       if isValidName(str: str){
           print("Valid")
       }else{
           print("Not valid")
       }
    }

check()

Hope it helps!

Vijay Sanghavi
  • 340
  • 1
  • 5
  • 23