【问题标题】:Regex for not containing consecutive characters不包含连续字符的正则表达式
【发布时间】:2018-07-25 03:05:00
【问题描述】:

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

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

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

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

【问题讨论】:

  • 请告诉我这不是密码格式要求。
  • 或许你可以写成/^[A-Z](?!.*__)(?:\w*[A-Z0-9])?$/i
  • 如果这是针对密码的,请参考Reference - Password Validation

标签: javascript regex


【解决方案1】:

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

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

见a demo on 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


作为JavaScriptsn-p:

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

请不要限制密码!

【讨论】:

  • 为什么是\n ??
  • 看起来棒极了。一个错误:'this_one__yes'
【解决方案2】:

你也可以使用

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

Demo

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

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

【讨论】:

  • 不适用于a 或b 或ab,请参阅regex101.com/r/QgbEYV/2(这意味着字符串必须至少有3 个字符长,不知道是否需要)。
【解决方案3】:

See regex in use here

^[a-z](?!\w*__)(?:\w*[^\W_])?$
  • ^ 断言位置为行首
  • [a-z] 匹配任何小写 ASCII 字母。下面的代码添加了i(不区分大小写)标志,因此这也匹配大写变量
  • (?!\w*__) 负前瞻确保字符串中不存在两个下划线
  • (?:\w*[^\W_])? 可选匹配以下
    • \w*匹配任意数量的单词字符
    • [^\W_] 匹配除_ 之外的任何单词字符。解释:匹配任何不是单词字符,但不是_(因为它在否定集中)。
  • $在行尾断言位置

let a = ['somestring', '_not_this_one', 'thisone_', 'neither this one', 'but_this_one', 'this__one_not', 'this_one__yes']
var r = /^[a-z](?!\w*__)(?:\w*[^\W_])?$/i

a.forEach(function(s) {
    if(r.test(s)) console.log(s)
});

【讨论】:

    猜你喜欢
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2012-05-11
    • 2011-04-11
    相关资源
    最近更新 更多