用户名的正则表达式以@开头

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

enter image description here

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.

Regex Demo

Example

$string = "My name is @john_doe from test@test.com";
preg_match("/(?<= |^)@[\w\d]+/", $string, $matches);   

print_r($matches);
// Array ( 
//     [0] => @john_doe 
// )

The following regex (using non-word boundary) should do it :

(^|\B)@\w+

see demo / explanation

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