Supersonic
Supersonic

Reputation: 430

Regular expression to to match alphanumeric followed by underscore and later alphanumeric

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.

Upvotes: 0

Views: 53

Answers (1)

Breandán Dalton
Breandán Dalton

Reputation: 1639

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)

Upvotes: 1

Related Questions