正则表达式在开始时删除空格

时间:2009-08-20 23:22:59

标签: php regex

简单的问题,但我很头疼解决这个游戏。示例正则表达式。

[a-zA-Z0-9\s]

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

让我知道

更新 regex from JG并且它正在运行。

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

4 个答案:

答案 0 :(得分:5)

尝试:

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

如果您只想要字母,数字和下划线,以及两个单词,不能少,不再需要:

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

没有下划线,

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

虽然,在一些正则表达式样式(特别是PHP,我现在看到的是目标)中,你使用它:

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

如果可以接受任何数量的此类单词和数字:

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

答案 1 :(得分:2)

为什么你真的要使用正则表达式?

trim(默认情况下)删除:

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

所以你需要的只是:

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

就是这样!

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

答案 2 :(得分:1)

根据我的理解,你想要一个正则表达式,它不允许你的字符串在开头或结尾都有空格。这些方面应该有用:

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

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"

输出:

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

答案 3 :(得分:0)

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