1

In a form I ask the user to insert his/her First name and Last name with only a space between them, and no space before and after them.

I found the following code: ^[a-zA-Z]+ [a-zA-Z]+$

But I would wish to put restrictions 15 letters max in first, and 20 letters max in last name.

Αρης
  • 45
  • 4
  • Asking basic usage of a regular expression pattern, I wonder about up-voters. – revo May 25 '17 at 08:08
  • Possible duplicate of [Set min and max characters in a regular expression?](https://stackoverflow.com/questions/15288519/set-min-and-max-characters-in-a-regular-expression) – revo May 25 '17 at 08:09

1 Answers1

6

Use a limiting quantifier:

^[a-zA-Z]{1,15} [a-zA-Z]{1,20}$
         ^^^^^          ^^^^^^

The {1,15} limiting quantifier tells the engine to match 1 to 15 characters matched with the subpattern that is located immediately to the left of it.

More from the docs:

The syntax is {min,max}, where min is zero or a positive integer number indicating the minimum number of matches, and max is an integer equal to or greater than min indicating the maximum number of matches. If the comma is present but max is omitted, the maximum number of matches is infinite. So {0,1} is the same as ?, {0,} is the same as *, and {1,} is the same as +. Omitting both the comma and max tells the engine to repeat the token exactly min times.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397