Using RegEx for validating First and Last names in Java -


i trying validate string contains first & last name of person. acceptable formats of names follows.

bruce schneier                   schneier, bruce schneier, bruce wayne o’malley, john f. john o’malley-smith cher 

i came following program validate string variable. validatename function should return true if name format matches of mentioned formats able. else should return false.

import java.util.regex.*;  public class telephone {      public static boolean validatename (string txt){         string regx = "^[\\\\p{l} .'-]+$";         pattern pattern = pattern.compile(regx, pattern.case_insensitive);         matcher matcher = pattern.matcher(txt);         return matcher.find();      }      public static void main(string args[]) {          string name = "ron o’’henry";          system.out.println(validatename(name));      } } 

but reason, returning false value. doing wrong here?

use this:

^[\p{l}\s.’\-,]+$ 

demo: https://regex101.com/r/dq8fk8/1

explanation:

  1. the biggest problem have ' , different. can achieve character copy pasting text.
  2. use \- instead of - in [] since mistaken range. example: [a-z]
  3. you can use \s instead of matching whitespaces.

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -