Home > Back-end >  Regex- Validation (validate string with not more than 1 space in between)
Regex- Validation (validate string with not more than 1 space in between)

Time:01-21

I am looking for a solution where I match a string without 2 or more spaces. I have checked multiple answer where they are giving the string where string have multiple spaces but I want the opposite like (abc bb) is my matching string not (abc bb or abc bb etc).

This my validation code

/^([A-Za-z0-9\_\- ] ){5,255}$/

What I am checking length should be 5 to 255 characters long and can have alphabets, numbers, -(hyphen), _(underscore) or space only.

** String without multiple spaces in between should not a valid match.

abc bb => match
abcd  => match
   bbv => match
abc  bb => not match
abc   bb => not match
abc    bb => not match

Thanks

CodePudding user response:

You might write the pattern as one of:

^(?=.{5,255}$) *[A-Za-z0-9_-] (?: [A-Za-z0-9_-] )* *$
^(?=.{5,255}$) *[\w-] (?: [\w-] )* *$

For example, the first pattern matches:

  • ^ Start of string
  • (?=.{5,255}$) Positive lookahead, assert 5 - 255 characters
  • * Match optional spaces
  • [A-Za-z0-9_-] Match 1 times any of the listed (without the space)
  • (?: [A-Za-z0-9_-] )* Optionally repeat the previous with a leading single space
  • * Match optional spaces
  • $ End of string

Regex demo

If there can be as most only 1 times a single space in between, you can change the quantifier from * to ? for the non capture group:

^(?=.{5,255}$) *[A-Za-z0-9_-] (?: [A-Za-z0-9_-] )? *$

Example code

$strings = [
    "abc bb",
    "abcd  ",
    "   bbv ",
    " abc  bb   ",
    "abc   bb",
    "abc    bb"
];
$pattern = "/^(?=.{5,255}$) *[A-Za-z0-9_-] (?: [A-Za-z0-9_-] )* *$/";
foreach ($strings as $s) {
    if (preg_match($pattern, $s)) {
        echo "Match for: [$s]" . PHP_EOL;
    } else {
        echo "No match for: [$s]" . PHP_EOL;
    }
}

Output

Match for: [abc bb]
Match for: [abcd  ]
Match for: [   bbv ]
No match for: [ abc  bb   ]
No match for: [abc   bb]
No match for: [abc    bb]

CodePudding user response:

You could try:

^(?!.*?\S .*? .*?\S)[\w -]{5,255}$

See an online demo


  • ^ - Start-line anchor;
  • (?!.*?\S .*? .*?\S) - A negative lookahead to prevent any line to have two space characters inbetween non-whitespace chars;
  • [\w -]{5,255} - Match any word-character, space or hyphen 5-255 times;
  • $ - End-line anchor.

Alternativey maybe:

.*?\S .*? .*?\S(*SKIP)(*F)|^[\w -]{5,255}$
  •  Tags:  
  • Related