Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  123] [ 5]  / answers: 1 / hits: 17163  / 6 Years ago, wed, february 14, 2018, 12:00:00

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.



^[a-zA-Z][a-zA-Z0-9_]+[a-zA-Z0-9]$

More From » regex

 Answers
39

You could use multiple lookaheads (neg. ones in this case):



^(?!.*__)(?!.*_$)[A-Za-z]w*$


See a demo on regex101.com.



Broken down this says:



^           # start of the line
(?!.*__) # neg. lookahead, no two consecutive underscores (edit 5/31/20: removed extra Kleene star)
(?!.*_$) # not an underscore right at the end
[A-Za-z]w* # letter, followed by 0+ alphanumeric characters
$ # the end




As JavaScript snippet:





let strings = ['somestring', '_not_this_one', 'thisone_', 'neither this one', 'but_this_one', 'this__one_not', 'this_one__yes']

var re = /^(?!.*__)(?!.*_$)[A-Za-z]w*$/;
strings.forEach(function(string) {
console.log(re.test(string));
});





Please do not restrain passwords!


[#55150] Monday, February 12, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ignacio

Total Points: 467
Total Questions: 128
Total Answers: 79

Location: Luxembourg
Member since Tue, Mar 14, 2023
1 Year ago
;