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:
- the biggest problem have
'
,’
different. can achieve character copy pasting text. - use
\-
instead of-
in[]
since mistaken range. example:[a-z]
- you can use
\s
instead ofmatching whitespaces.
Comments
Post a Comment