Home > Net >  Regular expression for a name that can contain not more than one space character
Regular expression for a name that can contain not more than one space character

Time:12-15

I'm struggling to find a regular expression that matches a name that can contain a space in it. So far this is what I've tried:

^(?![\s] $)(?![\s]{2,})[a-zA-Z\s]{2,25}$

Unfortunately I'm not so good on regex. The name can contain only letters and optionally a space character, and if a space is present there must be no more than one space character in the word. The whole name length (counting also the space) must be between 2 and 25 characters long. Here some examples of names that have to match:

  • Some Name
  • SingleWordName

Here some examples of names that have not to match the regular expression:

  • (a name full a space characters)
  • Some Name (two spaces between Some and Name)

The last requirement is that I have to use this regular expression both in javascript and php.

Thanks in advance!

CodePudding user response:

The pattern ^(?![\s] $)(?![\s]{2,})[a-zA-Z\s]{2,25}$ that you tried matches:

  • Assert that the string does not consist of 1 or more whitespace chars ^(?![\s] $)
  • Asserts not 2 or more whitespace chars at the beginning (?![\s]{2,})
  • Match 2-25 chars being either a-zA-Z or a whitespace char [a-zA-Z\s]{2,25}$

There is no restriction to match a single space in the whole string

Note that \s could also match a newline or a tab.


What you could do is assert 2-25 characters in the string.

Then match 1 chars a-zA-Z and optionally match a single space and 1 chars a-zA-Z

^(?=.{2,25}$)[a-zA-Z] (?: [a-zA-Z] )?$

The pattern matches:

  • ^ Start of string
  • (?=.{2,25}$) Positive lookahead, assert 2-25 chars in the string
  • [a-zA-Z] Match 1 chars A-Za-z
  • (?: [a-zA-Z] )? Optionally match and again 1 chars from the character class
  • $ End of string

See a regex demo.

CodePudding user response:

You could match the string with the following regular expression.

^(?!.* .* )[a-zA-Z ]{2,25}$

Demo

The elements of the expression are as follows.

^                # match beginning of string
(?!.* .* )       # negative lookahead asserts the string does not
                 # contain two (or more) spaces
[a-zA-Z ]{2,25}  # match between 2 and 25 letters and spaces
$                # match end of string
  • Related