本文介绍了不包含连续字符的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想不出满足所有这些要求的 javascript 正则表达式:
I can't figure out javascript regex that would satisfy all those requirements:
字符串只能包含下划线和字母数字字符.必须以字母开头,不能包含空格,不能以下划线结尾,并且不能包含两个连续的下划线.
这是我来的,但不包含连续的下划线"部分是最难添加的.
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]$
推荐答案
您可以使用多个前瞻(在本例中为否定的):
You could use multiple lookaheads (neg. ones in this case):
^(?!.*__)(?!.*_$)[A-Za-z]\w*$
请参阅 regex101.com 上的演示.分解为:
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
作为 JavaScript
片段:
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));
});
请不要限制密码!
这篇关于不包含连续字符的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!