字母数字值的正则表达式,而不是两个连续的下划线下划线

Regex for Alphanumeric Values and not two consecutive underscores underscore

我在 javascript 中要求为以下条件编写正则表达式

自定义元数据记录 MasterLabel 字段只能包含下划线和字母数字字符。它必须是唯一的,以字母开头,不包含空格,不以下划线结尾,并且不包含两个连续的下划线。

如果我们遗漏了独特的部分,因为我们必须用系统记录检查它,我需要一个正则表达式来测试上面提到的其他条件。

这是我到目前为止构建的表达式,但它似乎不起作用。我是正则表达式的新手,因此将不胜感激。

/^[a-zA-Z]([a-zA-Z0-9][^ ][^__])[^_]*$/

您可能正在寻找

^(?!_|\d)(?!.*__)(?!.*_$)\w+$

a demo on regex101.com


JavaScript中:

const regex = /^(?!_)(?!.*__)(?!.*_$)\w+$/gm;
const str = `_
A
abcd
_
123
some_spaces 
not_any_spaces__
1test34
correct_thing`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`${match}`);
    });
}

当且仅当它与以下正则表达式匹配时,该字符串才具有所有必需的属性:

/^[a-z][a-z\d]*(?:_[a-z\d]+)*$/i

Demo

正则表达式可以分解如下

/
^           # match beginning of string
[a-z]       # match a letter
[a-z\d]*    # match one or more alphanumeric characters
(?:         # begin non-capture group
   _        # match an underscore
  [a-z\d]+  # match one or more alphanumeric characters
)*          # end non-capture group and execute it zero or more times
$           # match end of string
/i          # specify matches of letters to be case-indifferent

请注意,我防止连续出现两个下划线的方法具有偶然性 side-effect 确保字符串中的最后一个字符不是下划线(免费赠品!)。