【发布时间】:2012-09-14 17:51:17
【问题描述】:
我正在学习正则表达式,所以请放轻松!
当不以_(下划线)开头并且仅包含单词字符(字母、数字和下划线本身)时,用户名被认为是有效的:
namespace Gremo\ExtraValidationBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class UsernameValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
// Violation if username starts with underscore
if (preg_match('/^_', $value, $matches)) {
$this->context->addViolation($constraint->message);
return;
}
// Violation if username does not contain all word characters
if (!preg_match('/^\w+$/', $value, $matches)) {
$this->context->addViolation($constraint->message);
}
}
}
为了将它们合并到一个正则表达式中,我尝试了以下方法:
^_+[^\w]+$
被解读为:如果以下划线开头(最终不止一个)并且如果后面至少有一个字符是不允许的(不是字母、数字或下划线),则添加违规。例如,不适用于“_test”。
你能帮我理解我哪里错了吗?
【问题讨论】:
标签: php regex preg-match