Using RegEx for validating First and Last names in Java

喜欢而已 提交于 2019-12-12 12:16:36

问题


I am trying to validate a String which contains the first & last name of a person. The acceptable formats of the names are as follows.

Bruce Schneier                  
Schneier, Bruce
Schneier, Bruce Wayne
O’Malley, John F.
John O’Malley-Smith
Cher

I came up with the following program that will validate the String variable. The validateName function should return true if the name format matches any of the mentioned formats able. Else it 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 for some reason, it is returning false for any value. What am I doing wrong here?


回答1:


Use this:

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

Demo: https://regex101.com/r/dQ8fK8/1

Explanation:

  1. The biggest problem you have is ' and is different. You can only achieve that character by copy pasting from the text.
  2. Use \- instead of - in [] since it will be mistaken as a range. For example: [a-z]
  3. You can use \s instead of for matching any whitespaces.



回答2:


You can do:

^[^\s]+,?(\s[^\s]+)*$



回答3:


You put too many backslashes in the regex: "^[\\\\p{L} .'-]+$"
After Java literal interpretation, that is: ^[\\p{L} .'-]+$
Which means match any combination of the following characters:

\  p  {  L  }  space  .  '  -

If you change to: "^[\\p{L} .'-]+$"
Regex will see: ^[\p{L} .'-]+$
Which means match any combination of the following characters:

letters  space  .  '  -

BUT: Don't validate names.

See What are all of the allowable characters for people's names?, which leads to Personal names around the world.

In short: You can't, so don't.



来源:https://stackoverflow.com/questions/36831572/using-regex-for-validating-first-and-last-names-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!