简体   繁体   中英

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 :

[@username:4]

where 'username' can be any text and '4' can be any integer . 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+

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

If the username would never have brackets then use the following:

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

It also makes the :integer part optional

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

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

\\w means all word can be username, it supports az,AZ,0-9 and _

\\d means all digital, 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). Therefore the longest username is 25 characters long and the shortest possible is 1 character long. 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.

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