Problem to add @ in regex

Hi guys, I would like to ask your help for a regex. I need a regex to accept any string starting with @, following after with any alphanumeric characters or - character, and at the end the : character. I am not the best with regex :smiling_face_with_tear:

I tried that filter, but doesn’t work:

/@[a-z0-9\-]:/.match("@a12-3:")

Any idea ?

The regex [a-z0-9\-] only matches a single character. It also doesn’t handle uppercase letters if that’s a concern. To match more than one character you need to use a + at the end, assuming you do not want @: to be valid. Otherwise * would allow for that to be valid. So try /@[a-z0-9\-]+:/.

2 Likes

For this kind of thing I often use https://rubular.com/ which allows to see the matches of a regex applied on an input string before using the regex for real… Far easier than trial and error on real code

Crystal doesn’t use the same engine Ruby does, so you’d be better off using https://regexr.com/, making sure it’s set to PCRE.

2 Likes