0

I am not so great at regular expressions so I would like to understand if the regular expression which I have made is ok or it can be improved.

Regular expression conditions:

  1. Maximum 20 characters allowed.
  2. First 3 - 4 characters should be alphanumeric. It can either be 3 or 4 characters.
  3. The next character should be a underscore(_) only.
  4. Followed by that there can be another 1-15 alphanumeric characters.

I have made a regular expression like this :

^[[:alnum:]]{3,4}(_)[[:alnum:]]{1,15}$

Is this a good practice or can I improve further?

Thanks for your help in advance.

Supersonic
  • 430
  • 1
  • 11
  • 35
  • Please comment and let me know after down voting. As I am learning I really do not know the reason behind down vote. Thanks – Supersonic Jun 20 '18 at 09:00
  • 1
    I upvoted your question to counter the previous downvote. I don't see why anyone would downvote this question and not give a reason. Perhaps it was for adding the ruby tag (since there's nothing about ruby in the question)? – Breandán Dalton Jun 20 '18 at 09:03
  • @BreandánDalton Thanks removed it. Instead of ^ and $ can I use \A and \z respectively? – Supersonic Jun 20 '18 at 09:09

1 Answers1

1

Your expression correctly fulfills the conditions you specify. In addition, it also captures the underscore, which you don't need to do. So you could simply write

^[[:alnum:]]{3,4}_[[:alnum:]]{1,15}$

Also, as you are aware, this expression matches the entire line, not just a portion of a line, so whitespace at either end of the string could cause you problems if the line could contain it (cf UNIX/Windows different line endings).

What is the difference between ^ and \A , $ and \Z in regex? shows the difference between \A \z and ^ $ (including an interesting comment about \z and trailing newline)

Breandán Dalton
  • 1,619
  • 15
  • 24