javaregex

Regular expression to validate a name


I'm trying to create a regex that satisfies the following:

Here's what I got so far:

^[A-Z][a-zA-z ]{1,29}$

If I put a [^ ] at the end, it allows a special character.


Solution

  • You can use

    ^[A-Z](?=.{1,29}$)[A-Za-z]*(?:\h+[A-Z][A-Za-z]*)*$
    

    The pattern matches:

    Regex demo

    In Java with the doubled backslashes

    String regex = "^[A-Z](?=.{1,29}$)[A-Za-z]*(?:\\h+[A-Z][A-Za-z]*)*$";