简体   繁体   中英

Regular expression for username start with @

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM