简体   繁体   English

如何为字符串创建正则表达式以匹配[@username:4]?

[英]How do I create regular expression for a string to match [@username:4]?

I need to create a regular expression to detect a string matching the format below for Java and Php : 我需要创建一个正则表达式来检测匹配以下Java和Php格式的字符串:

[@username:4] [@用户名:4]

where 'username' can be any text and '4' can be any integer . 其中“用户名”可以是任何文本“ 4”可以是任何整数 I tried creating one myself but I am new to the world of regular expressions and was unable to do so. 我曾尝试自己创建一个,但是我对正则表达式领域并不陌生,因此无法做到。 This is the furthest I got : 这是我得到的最远的信息:

([[]+[@]+[A-Za-z0-9])\\w+ ([[] + [@] + [A-Za-z0-9])\\ w +

Any help will be great.Thanks! 任何帮助都会很棒。谢谢!

Would the username ever have :'s in it? 用户名中是否会包含:? If not use the following 如果不使用以下

\[@([^:]+):(\d+)\]

https://regex101.com/r/7iqrPm/1 https://regex101.com/r/7iqrPm/1

If the username would never have brackets then use the following: 如果用户名永远不会带有方括号,请使用以下命令:

\[@([^:\]]+)(?::(\w+))?\]

It also makes the :integer part optional 它还使:integer部分成为可选

https://regex101.com/r/FmfAze/3 https://regex101.com/r/FmfAze/3

\[@\w+\:\d+\]

\\w means all word can be username, it supports az,AZ,0-9 and _ \\w表示所有单词都可以是用户名,它支持az,AZ,0-9 and _

\\d means all digital, 0-9 \\d表示所有数字, 0-9

A quick way of doing it would be to use this regular expression: 一种快速的方法是使用以下正则表达式:

\[@\w+:\d+\]

Test Here 在这里测试
which does what you asked for but has a disadvantage. 这可以满足您的要求,但有一个缺点。 It doesn't take the length of the username or the integer into account. 它不考虑用户名或整数的长度。

I don't know if it is important in your case but i personally would prefer this regex: 我不知道这对您来说是否重要,但我个人更希望使用此正则表达式:

\[@\w{1,25}:\d{1,5}\]

Test Here 在这里测试
Which does exactly the same as the one above but doesn't allow for infinitely long username or number and sets the bounds for both. 与上一个完全相同,但不允许无限长的用户名或数字,并设置了两者的界限。 In perticular, \\w{1,25} means that it will match any word character (a-zA-Z0-9_) between 1 and 25 times (inclusive). 在垂直位置, \\w{1,25}表示它将与1到25次(含)之间的任何单词字符(a-zA-Z0-9_)匹配。 Therefore the longest username is 25 characters long and the shortest possible is 1 character long. 因此,最长的用户名长度为25个字符,最短的用户名长度为1个字符。 These values can be tweaked. 这些值可以调整。 Likewise it restricts the integer length between 1 and 5 characters therefore any integer with more than 5 digits or less than 1 is invalid: \\d{1,5} Again, the values can be tweaked. 同样,它将整数长度限制在1到5个字符之间,因此任何大于5位或小于1的整数都是无效的: \\d{1,5}同样,可以调整值。

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

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