简体   繁体   English

PHP正则表达式模式,用于匹配用户名

[英]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. 我正在开发一个laravel应用程序,用户可以在其中通过将用户名输入适当的形式来引用其个人资料。

Let's see an example: 让我们来看一个例子:

A user named John can refer to his profile using the following text: @John 名为John的用户可以使用以下文本引用其个人资料:@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]+) 我花了几个小时试图了解正则表达式的工作原理,但是到目前为止,这种模式是我现在所要做的: @([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. 例如:@ John,@ Sam,@ Bill等。

It shouldn't match a string that doesn't start with the @ symbol. 它不应与不以@符号开头的字符串匹配。 For example: a@John, something@Sam, 123@Bill, etc. 例如:a @ John,something @ Sam,123 @ Bill等。

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 例如:@John @,@ Sam @ something,@ Bill @@ sometext等。在这种情况下,模式应捕获: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 尝试/(?:\\s@{1,3})([a-zA-Z@.]+)/i


Explain 说明

@ Character. @角色。 Matches a "@" character (char code 64). 匹配一个“ @”字符(字符代码64)。 {1,3} Quantifier. {1,3}量词。 Match between 1 and 3 of the preceding token. 在前一个令牌的1和3之间匹配。

\\w Word. \\ w字。 Matches any word character (alphanumeric & underscore). 匹配任何单词字符(字母数字和下划线)。 + Plus. +加号。 Match 1 or more of the preceding token. 匹配1个或多个前面的令牌。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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