Regex for validation on first n character

Viewed 154

Can someone help me with the regular expression for the following requirement.

  • Input should be at least 1 character and can contain maximum of 79 characters.
  • Only alphabets and whitespace ([a-zA-Z ]{1,79})
  • If the length exceeds 24 characters, then it should contain at least one whitespace.
2 Answers

You might use

^(?:[a-zA-Z]{1,24}|(?=.{1,79}$)[a-zA-Z]* [a-zA-Z ]*)$

The pattern matches

  • ^ Start of string
  • (?: Non capture group
    • [a-zA-Z]{1,24} Match 1-24 times a char a-zA-Z
    • | Or
    • (?=.{1,79}$) Positive lookahead to assert 1-79 chars
    • [a-zA-Z]* [a-zA-Z ]* Match optional chars a-zA-Z followed by a space and optional chars a-zA-Z and a space
  • ) Close non capture group
  • $ End of string

Regex demo

Assuming you also want to avoid leading/trailing/double spaces, you could try:

^(?!\S{25,}$|.{80})[a-z]+(?: [a-z]+)*$
  • ^ - Start line anchor.
  • (?! - Open negative lookahead:
    • \S{25,}$ - Any 25 (or more) non-whitespace characters up to the end.
    • | - Or:
    • .{80} - Any 80 characters other than newline.
    • ) - Close negative lookahead.
  • [a-z]+ - 1+ alphabets.
  • (?: - Open non-capturing group:
    • [a-z]+ - A literal space followed by 1+ alphabets.
    • )* - Close non-capturing group and match it 0+ times.
  • $ - End line anchor.

See the demo.


Note: If you don't mind about spaces, then you can use ^(?!\S{25,}$|.{80})[a-z ]+$ essentially also allowing for input like .

Related