Regular expression. 20 alphabetic letters and up to 2 of (. - _)
I am trying to create a regex pattern for an html input field that only allows up to 20 combined alphabetic letters and numbers, which can only contain up to two of hyphen (-), underscore (_), and full stop (.)
So something like only two characters are allowed and any number of letters and numbers are allowed, in combination they must be between 4 and 20.
What would be the template for this?
An example (non-functional) version could be like [A-Za-z0-9([\._-]{0,2})]{4,20}
Decision:
I decided to go with @pascalhein @ Honore Doktorr's answer, which is to use lookahead. The final template^(?=[A-Za-z0-9]*([._-][A-Za-z0-9]*){0,2}$)[A-Za-z0-9._-]{4,20}$
source to share
You can check the length with lookahead at the beginning:
^(?=.{4,20}$)
Then list all the cases that are allowed for your regex separately:
[A-Za-z0-9]* (no special chars)
[A-Za-z0-9]*[._-][A-Za-z0-9]* (one special char)
[A-Za-z0-9]*[._-][A-Za-z0-9]*[._-][A-Za-z0-9]* (two special chars)
It's not pretty, but I believe it should work. This is the final expression:
^(?=.{4,20}$)([A-Za-z0-9]*|[A-Za-z0-9]*[._-][A-Za-z0-9]*|[A-Za-z0-9]*[._-][A-Za-z0-9]*[._-][A-Za-z0-9]*)$
Edit:
In fact, it would be better to check the number of special characters with a lookahead:
^(?=[A-Za-z0-9]*([._-][A-Za-z0-9]*){0,2}$)[A-Za-z0-9._-]{4,20}$
source to share
I urge you not to use regex if there are functions for the breed you want to achieve.
The advice I give jrs on this topic is to use regex for single viruses, if there is more than one breed, use more regex.
to answer your question:
-
1 your valid characters from start to finish.
var 1stregex = / ^ [A-Za-z0-9 ._-] {4,20} $ /;
-
2 Count must be between 0 and 2, which is .match () in javascript. length.
var 2ndregex = / ([._-]) /;
if (myText.match (1stregex) & myText.match (2ndregex) .length <= 2) {isvalid = true; }
source to share