Skip to content
Advertisement

How can i “merge” these two regular expression in PHP?

I’m learning regular expression, so please go easy with me!

Username is considered valid when does not start with _ (underscore) and if contains only word characters (letters, digits and underscore itself):

namespace GremoExtraValidationBundleValidatorConstraints;

use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintValidator;

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

In order to merge them in one regular expression, i’ve tried the following:

^_+[^w]+$

To be read as: add a violation if starts with an underscore (eventually more than one) and if at least one character following is not allowed (not a letter, digit or underscore). Does not work with “_test”, for example.

Can you help me to understand where I’m wrong?

Advertisement

Answer

You can add a negative lookahead assertion to your 2nd regex:

^(?!_)w+$

Which now means, try to match the entire string and not any part of it. The string must not begin with an underscore and can have one or more of word characters.

See it work

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement