不包含连续字符的正则表达式

新手上路,请多包涵

我想不出满足所有这些要求的 javascript 正则表达式:

该字符串只能包含下划线和字母数字字符。它必须以字母开头,不包含空格,不以下划线结尾,并且不包含两个连续的下划线。

据我所知,但“不包含连续下划线”部分是最难添加的。

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

原文由 Mariusz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 889
2 个回答

您可以使用多个前瞻(在这种情况下为负):

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

请参阅 regex101.com 上的演示


分解说:

 ^           # 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));
});

请不要限制密码!

原文由 Jan 发布,翻译遵循 CC BY-SA 4.0 许可协议

您也可以使用

^[a-zA-Z]([a-zA-Z0-9]|(_(?!_)))+[a-zA-Z0-9]$

演示

与您的正则表达式相比,唯一的变化是将 [a-zA-Z0-9_] 更改为 [a-zA-Z0-9]|(_(?!_)) 。我从字符集中删除了下划线,如果后面没有下划线,则允许它出现在备选方案的第二部分。

(?!_) 是负先行意味着 _ 不能是下一个字符

原文由 mrzasa 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题