Regex for not containing consecutive characters

后端 未结 3 1762
鱼传尺愫
鱼传尺愫 2021-01-06 06:48

I can\'t figure out javascript regex that would satisfy all those requirements:

The string can only contain underscores and alphanumeric characters. It must

3条回答
  •  攒了一身酷
    2021-01-06 07:20

    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!

提交回复
热议问题