I can’t figure out javascript regex that would satisfy all those requirements:
The string can only contain underscores and alphanumeric characters. It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.
This is as far as I came, but ‘not containing consecutive underscores’ part is the hardest to add.
JavaScript
x
2
1
^[a-zA-Z][a-zA-Z0-9_]+[a-zA-Z0-9]$
2
Advertisement
Answer
You could use multiple lookaheads (neg. ones in this case):
JavaScript
1
2
1
^(?!.*__)(?!.*_$)[A-Za-z]w*$
2
Broken down this says:
JavaScript
1
6
1
^ # start of the line
2
(?!.*__) # neg. lookahead, no two consecutive underscores (edit 5/31/20: removed extra Kleene star)
3
(?!.*_$) # not an underscore right at the end
4
[A-Za-z]w* # letter, followed by 0+ alphanumeric characters
5
$ # the end
6
As
JavaScript
snippet:
JavaScript
1
6
1
let strings = ['somestring', '_not_this_one', 'thisone_', 'neither this one', 'but_this_one', 'this__one_not', 'this_one__yes']
2
3
var re = /^(?!.*__)(?!.*_$)[A-Za-z]w*$/;
4
strings.forEach(function(string) {
5
console.log(re.test(string));
6
});
Please do not restrain passwords!