Başında boşluk kaldırmak Regex

3 Cevap php

Basit bir soru ama ben bu oyunu çözmek için bir baş ağrısı var. Örnek regex.

[a-zA-Z0-9\s]

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

Bana haber ver

Update regex from JG ve çalışıyor.

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;
}

3 Cevap

Anladığım kadarıyla, siz dize başında boşluk, ya da sonunda ya var izin vermeyen bir regex istiyorum. Bu satırlar boyunca bir şey çalışması gerekir:

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

Python bir örnek:

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"

Çıktı:

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

Deneyin:

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

Harfleri ve sayıları ve alt ve iki kelime, sadece isterseniz daha az, daha fazla:

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

Hiçbir çizgi için,

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

Rağmen, bazı Regex stilleri (şimdi bakınız özellikle PHP, hedef), bu kullanın:

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

Bu tür kelime ve sayı herhangi bir sayı kabul edilebilir ise:

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

Neden yeryüzünde bunun için regex kullanmak isteyeyim?

(varsayılan) Döşeme kaldırır:

*    " " (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.

böylece tüm ihtiyacınız:

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

Ve o kadar!

$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 ;)