I want to capture all the username that starts with @ symbol and also there is no character before it.
Until now I have a regular expression that could get all the usernames but it also fetches the usernames that have characters before it but i want to ignore them.
/@[\w\d]+/g
You can use a positive look behind to verify that the @
is preceded by space or start of the string.
(?<= |^)@[\w\d]+
(?<= |^)
Positive look behind. Ensures that @
is preceded by
space or ^
start of the string. Not the look aheads, doesn't consume any characters, it just checks.Example
$string = "My name is @john_doe from test@test.com";
preg_match("/(?<= |^)@[\w\d]+/", $string, $matches);
print_r($matches);
// Array (
// [0] => @john_doe
// )
You just need to add ^. So the regex looks like /^@[\w\d]+/g
Just need to add the term to check @ is at the begining
/^@[\w\d]+/g