Lucas Lucas - 1 year ago 83
Java Question

Regex for consistent Person Name

I'm a newbie in Regex!!!!

Can someone expert help me with validation for Person name?

I need to validate and throw error if:

• Duplicity in first letter
• Number in first letter


Answer Source

For the validations you describe, regex isn't the way to go. (And regex is one of my favorite things in the world, so it pains me to say that.) Instead, you'll get far more readable, debuggable code by just using the basic methods from the String class.

By "duplicity in first letter", do you mean to check if the first two letters are the same? If so, then validation could throw an error for a valid name such as "Aaron". (Depending on how you handle case.) If this is still absolutely necessary, use this:
if (name.charAt(0).equalsIgnoreCase(name.charAt(1))) // Throw your error.

As far as trimming the string, you're generally better off just using the string's .trim() method to correct the error instead of failing validation. If, for some reason, you need to throw an error, use this:
if (name.length() != name.trim.length()) // Throw your exception.

Finally, for checking if the first letter is a digit, you want charAt() and Character.isDigit(), like this:
if (Character.isDigit(name.charAt(0)) // Throw your exception.

(See this question for more information on the first-letter-is-number problem.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download