开发者

Java regex to validate a name

开发者 https://www.devze.com 2023-01-07 05:26 出处:网络
To validate names that can be John, John Paul, etc. I use this regex: String regex = \"[A-Z]([a-z]+|\\\\s[a-z]+)\";

To validate names that can be

John, John Paul, etc.

I use this regex:

String regex = "[A-Z]([a-z]+|\\s[a-z]+)";

but when I do:

boolean ok = Pattern.matches(regex, 开发者_Go百科"John Paul");

the matches fail?

Why? I want to use matches to validate the string as whole...

Is that regex wrong?


You are going to have lots of problems with validating names - there are lots of different types of names. Consider:

  • Jéan-luc Picard
  • Carmilla Parker-Bowles
    • Joan d'Arc
  • Matt LeBlanc
  • Chan Kong-sang (Jackie Chan's real name)
  • P!nk
  • Love Symbol #2

The easiest thing to do is to get the user to enter their name and accept it as is. If you want to break it up into personal name and family names for things such as personalisation, then I suggest you break up the input fields into two (or more) parts, or simply ask for a "preferred name" or "nickname" field.

I doubt you'll find a regex that can validate all the variety of names out there - get a big set of sample data (preferably real-world) before you start trying.


Paul has a capital P and your regex doesn't allow for capitalization at the start of the second word.


Try something like this:

[A-Z][a-z]+( [A-Z][a-z]+)?

The ? is an optional part that matches the last name. This captures the last name (with a preceding space) in group 1. You can use a non-capturing group (?:...) if you don't need this capture.

References

  • regular-expressions.info - Question Mark for Optional

Problem with original pattern

Here's the original pattern:

[A-Z]([a-z]+|\s[a-z]+)

Expanding the alternation this matches:

[A-Z][a-z]+

Or:

[A-Z]\s[a-z]+

This does match John, and J paul, but it clearly doesn't match John Paul.

0

精彩评论

暂无评论...
验证码 换一张
取 消