gre*_*emo 4 php regex username preg-match
我正在学习正规表达,所以请跟我一起轻松!
如果不以_(下划线)开头且仅包含单词字符(字母,数字和下划线本身),则用户名被视为有效:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了在一个正则表达式中合并它们,我尝试了以下内容:
^_+[^\w]+$
Run Code Online (Sandbox Code Playgroud)
要读作:如果以下划线(最终多于一个)开头并且如果不允许至少一个字符(不是字母,数字或下划线),则添加违规.例如,不适用于"_test".
你能帮我理解我错在哪里吗?
您可以在第二个正则表达式中添加负前瞻断言:
^(?!_)\w+$
Run Code Online (Sandbox Code Playgroud)
现在意味着,尝试匹配整个字符串而不是它的任何部分.该字符串不能以下划线开头,并且可以包含一个或多个单词字符.