Ark
Ark

Reputation: 15

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!

Upvotes: 0

Views: 80

Answers (3)

vanzand
vanzand

Reputation: 41

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

\w means all word can be username, it supports a-z,A-Z,0-9 and _

\d means all digital, 0-9

Upvotes: 1

fill͡pant͡
fill͡pant͡

Reputation: 1165

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.

Upvotes: 0

Maslo
Maslo

Reputation: 282

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

Upvotes: 2

Related Questions