Regex for not containing consecutive characters

后端 未结 3 1763
鱼传尺愫
鱼传尺愫 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:16

    See regex in use here

    ^[a-z](?!\w*__)(?:\w*[^\W_])?$
    
    • ^ Assert position as the start of the line
    • [a-z] Match any lowercase ASCII letter. The code below adds the i (case-insensitive) flag, thus this also matches the uppercase variables
    • (?!\w*__) Negative lookahead ensuring two underscores do not exist in the string
    • (?:\w*[^\W_])? Optionally match the following
      • \w* Match any number of word characters
      • [^\W_] Match any word character except _. Explained: Match anything that is not not a word character, but not _ (since it's in the negated set).
    • $ Assert position at the end of the line

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

提交回复
热议问题