2

Cont from unable to regex certain pattern

I have the following regular expression:

^(?!.*  )[^#+&\'\"\\\\]*$

Now I want to fulfill the followings:

""      ---> invalid
" "     ---> invalid
" a"    ---> invalid
"a b"   ---> valid
"a  b"  ---> invalid

Can someone help me?

Community
  • 1
  • 1
KKL Michael
  • 795
  • 1
  • 13
  • 31

2 Answers2

1

You can use this regex:

^(?!^.*\s{2}.*$)[^\s][^#+&'"\\\n\r]*[^\s]$

In php:

$re = "/^(?!^.*\\s{2}.*$)[^\\s][^#+&'\"\\\\\\n\\r]*[^\\s]$/m"; 

See demo


(?!^.*\s{2}.*$) will ensure that the string doesn't contains consecutive spaces.

^[^\\s][^#+&'\"\\\\\\n\\r]*[^\\s]$ will ensure that the string doesn't contain leading nor trailing spaces.

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

You can use

^[^#+&'"\\\s]+(?:\s[^#+&'"\\\s]+)*$

PHP:

$re = '~^[^\s#+&\'"\\\\]+(?:\s[^\s#+&\'"\\\\]+)*$~';

See the regex demo. This regex does not allow consequent whitespaces and any leading/trailing whitespaces, is linear and fast.

Details:

  • ^ - start of string
  • [^#+&'"\\\s]+ - 1+ chars other than whitespace and any of #, +, &, ', ", \ chars
  • (?:\s[^#+&'"\\\s]+)* - zero or more sequences of:

    • \s - whitespace (1 time)
    • [^#+&'"\\\s]+ - 1+ chars other than whitespace and any of #, +, &, ', ", \ chars
  • $ - end of string (replace with \z for safer matching)

Here is an IDEONE PHP demo that only echos Matched 'a b':

if (preg_match('~^[^\s#+&\'"\\\\]+(?:\s[^\s#+&\'"\\\\]+)*$~', "")) {
    echo "Matched ''\n";
}
if (preg_match('~^[^\s#+&\'"\\\\]+(?:\s[^\s#+&\'"\\\\]+)*$~', " ")) {
    echo "Matched ' '\n";
}
if (preg_match('~^[^\s#+&\'"\\\\]+(?:\s[^\s#+&\'"\\\\]+)*$~', " a")) {
    echo "Matched ' a'\n";
}
if (preg_match('~^[^\s#+&\'"\\\\]+(?:\s[^\s#+&\'"\\\\]+)*$~', "a b")) {
    echo "Matched 'a b'\n";
}
if (preg_match('~^[^\s#+&\'"\\\\]+(?:\s[^\s#+&\'"\\\\]+)*$~', "a  b")) {
    echo "Matched 'a  b'\n";
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563