Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow letters, one space between words and a total length of 50

Tags:

c#

regex

I'm trying to build a regular expression with the following conditions:

  • Only letters
  • One space between words (no more than one space)
  • Maximum length 50

And this is what I have done so far:

^(([A-Za-z]+( [A-Za-z])+){1,50})$

This allows me to validate the spaces between words and only letters conditions but it is not working for the length and it's not working for words without spaces, example:hello. Can someone help me with this?

Example:

What I need: Regex that allows sentences (with max length 50) like this:

Hello this is an example
Hello
a b c
like image 245
Melissa Pérez Cadavid Avatar asked Oct 15 '25 16:10

Melissa Pérez Cadavid


1 Answers

Try this:

^\b(?!.*?\s{2})[A-Za-z ]{1,50}\b$

Demo

[A-Za-z ]{1,50} will check for the characters and length, while the negative lookahead (?!.*?\s{2}) will check for the spaces condition. (\b) to disallow white space at ends.

like image 160
Lucas Trzesniewski Avatar answered Oct 18 '25 05:10

Lucas Trzesniewski