简体   繁体   中英

PHP regex pattern for matching username

I'm developing a laravel application where a user can refer to his profile by putting his username in the appropriate form.

Let's see an example:

A user named John can refer to his profile using the following text: @John

I spent several hours trying to understand how regex works, but this pattern is where i've got so far: @([A-Za-z0-9]+)

This pattern perfectly matches the example above, but it also matches other formats that it normally shouldn't.

I need some help creating the perfect pattern.

It should only match a string that starts with the @ symbol. For example: @John, @Sam, @Bill, etc.

It shouldn't match a string that doesn't start with the @ symbol. For example: a@John, something@Sam, 123@Bill, etc.

It should also match those formats that contain more than one @ symbols. For example: @John@, @Sam@something, @Bill@@sometext, etc. In this case the pattern should capture: John@, Sam@something, Bill@@sometext

Thanks for your help and sorry for my bad english.

This should work:

(?<=\s|^)@([\w@]+)

There is a positive lookbehind assertion to make sure the tag is preceded by whitespace, or the start of the string. After that it's just a case of consuming the @ character and putting the username inside a capturing group.

Regex demo

Your regex is almost correct. Firstly, you want to say that your regex should match also the begining of the string. You can achieve that with caret symbol (^):

^@([A-Za-z0-9]+)

Secondly, you want to be able to put the @ sign inside. Now it's easy - just add that symbol inside the brackets.

^@([A-Za-z0-9@]+)

Try /(?:\\s@{1,3})([a-zA-Z@.]+)/i


Explain

@ Character. Matches a "@" character (char code 64). {1,3} Quantifier. Match between 1 and 3 of the preceding token.

\\w Word. Matches any word character (alphanumeric & underscore). + Plus. Match 1 or more of the preceding token.

Here is regexr: http://regexr.com/3djhq

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