I have a username to test:
I have written this regex
^[a-zA-Z][^\W_]{2,}_?[a-zA-Z0-9]$
But I really have no idea how to limit the appearance of underscore (0-1 times).
How can I achieve my requirements?
Use a lookahead to check the more-specific qualifications, then apply the general rule of \w{4,}.
const tests = ['_und', 'u_nd', 'un_d', 'und_', 'u_n_', 'u__d', '8_no'];
for (i in tests) {
document.write(tests[i] + ' => ' + /^(?=[a-z][^_]*_?[^_]+$)\w{4,}$/i.test(tests[i]) + "<br>");
}
(?= #lookahead
[a-z] #a letter
[^_]* #zero or more non-underscores
_? #an optional underscore
[^_]+$ #one or more non-underscores until the end of the string
)
It can also be done without a lookahead but the length check of 4 or more characters becomes implicit instead of explicit. In other words, humans who read the pattern will need to determine the the minimum length of the string is 4 by understanding conditional expressions and summing the implemented quantifiers.
const tests = [
'und',
'_und',
'u_nd',
'un_d',
'und_',
'u_n_',
'u__d',
'8_no',
'u_derscore',
'un_erscore',
'und_rscore',
'unde_score',
'under_co_e',
'underscor_',
'_nderscore'
];
for (i in tests) {
document.write(tests[i] + ' => ' + /^[a-z](?:_[^\W_]{2,}|[^\W_]_[^\W_]+|[^\W_]{2,}_?[^\W_]+)$/i.test(tests[i]) + "<br>");
}
Breakdown:
/ #pattern delimiter
^ #start of string anchor
[a-z] #alphabetical character
(?: #non-capturing group
_[^\W_]{2,} #underscore, two or more alnum characters (at least 3 characters)
| #or
[^\W_]_[^\W_]+ #alnum character, underscore, one or more non-underscore (at least 3 characters)
| #or
[^\W_]{2,}_?[^\W_]+ #two or more alnum characters, optional underscore, one or more alnum characters (at least 3 characters)
) #end of non-capturing group
$ #end of string anchor
/ #pattern delimiter
i #case-insensitive pattern modifier