wow
wow

Reputation: 8259

Regex remove whitespace at beginning

Simple question but I got a headache to solve this game. Example regex.

[a-zA-Z0-9\s]

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

Let me know

Update regex from JG and it's working.

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 = 'Stack Overflow ';
$validator = regex($str);

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

Upvotes: 2

Views: 1827

Answers (4)

5929
5929

Reputation:

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

Upvotes: 0

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297305

Try:

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

If you want only letters and numbers and underscores, and two words, no less, no more:

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

For no underscore,

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

Though, in some Regex styles (particularly PHP, which I see now is the target), you use this:

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

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

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

Upvotes: 5

aeiou
aeiou

Reputation:

Why on earth would you want to use regex for this?

trim (by 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 that is it!

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

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

http://codepad.org/fYNfob6y ;)

Upvotes: 2

João Silva
João Silva

Reputation: 91369

From what I understood, you want a regex that doesn't allow your string to have either whitespace at the beginning, or at the end. Something along these lines should work:

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

An example in Python:

import re
test = ["Stack Overflow",
        "Stack&!Overflow",
        " Stack Overflow",
        "Stack Overflow ",
        "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
'Stack Overflow ' => non-match
'x' => match
'' => match
' ' => non-match

Upvotes: 1

Related Questions