Regex removes leading spaces

Simple question, but I got a headache to solve this game. Regex example.

[a-zA-Z0-9\s]

[whitespace]Stack[whitespace]Overflow - not allow
Stack[whitespace]Overflow - allow
Stack[whitespace]Overflow[whitespace] - not allow

      

Tell me

Update regex from JG and it works.

function regex($str)
{
    $check = preg_replace('/^[a-zA-Z0-9][a-zA-Z0-9\s]+[a-zA-Z0-9]$|^[a-zA-Z0-9]*$/', "", $str);

    if (empty($check)) {
        return true;
    } else {
        return false;
    }
}

$str = 'Qaru ';
$validator = regex($str);

if ($validator) {
    echo "OK » " .$str;
} else {
    echo "ERROR » " . $str;
}

      

+2


source to share


4 answers


From what I understood, you need a regex that prevents your string from having either leading or trailing spaces. Something along these lines should work:

/^[a-zA-Z0-9][a-zA-Z0-9\s]+[a-zA-Z0-9]$|^[a-zA-Z0-9]*$/

      

Example in Python:



import re
test = ["Stack Overflow",
        "Stack&!Overflow",
        " Stack Overflow",
        "Qaru ",
        "x",
        "", 
        " "]
regex = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9\s]+[a-zA-Z0-9]$|^[a-zA-Z0-9]*$')
for s in test:
    print "'"+s+"'", "=>", "match" if regex.match(s) != None else "non-match"

      

Output:

'Stack Overflow' => match
'Stack&!Overflow' => non-match
' Stack Overflow' => non-match
'Qaru ' => non-match
'x' => match
'' => match
' ' => non-match

      

+1


source


Try:

/^\S.*\S$|^\S$/

      

If you only want letters and numbers and underscores, plus two words, at least:

/^\w+\s+\w+$/

      

No underline



/^\p{Alnum}+\s+\p{Alnum}+$/

      

Although in some Regex styles (especially PHP I see now), you use this:

/^[[:alnum:]]+\s+[[:alnum:]]+$/

      

If any number of such words and numbers can be accepted:

/^\w[\w\s]*\w$|^\w$/

      

+5


source


Why would you want to use a regular expression for this?

trim (default) removes:

*    " " (ASCII 32 (0x20)), an ordinary space.
* "\t" (ASCII 9 (0x09)), a tab.
* "\n" (ASCII 10 (0x0A)), a new line (line feed).
* "\r" (ASCII 13 (0x0D)), a carriage return.
* "\0" (ASCII 0 (0x00)), the NUL-byte.
* "\x0B" (ASCII 11 (0x0B)), a vertical tab.

      

so all you need is:

function no_whitespace($string)
{
      return trim($string) === $string;
}

      

And it's all!

$tests = array
(
    ' Stack Overflow',
    'Stack Overflow',
    'Qaru '
);

foreach ($tests as $test)
{
   echo $test."\t:\t".(no_whitespace($test) ? 'allowed' : 'not allowed').PHP_EOL;
}

      

http://codepad.org/fYNfob6y ;)

+2


source


if ($string =~ /^\S.*\S$/){
   print "allowed\n";
} else {
   print "not allowed\n";
}

      

0


source







All Articles