我需要在 javascript 中為以下條件撰寫正則運算式
自定義元資料記錄 MasterLabel 欄位只能包含下劃線和字母數字字符。它必須是唯一的,以字母開頭,不包含空格,不以下劃線結尾,并且不包含兩個連續的下劃線。
如果我們遺漏了唯一部分,因為我們必須使用系統記錄檢查它,我需要一個正則運算式來測驗上面提到的其他條件。
這是我迄今為止構建的一個運算式,但它似乎不起作用。我是正則運算式的新手,所以任何幫助將不勝感激。
/^[a-zA-Z]([a-zA-Z0-9][^ ][^__])[^_]*$/
uj5u.com熱心網友回復:
當且僅當字串與以下正則運算式匹配時,該字串才具有所有必需的屬性:
/^[a-z][a-z\d]*(?:_[a-z\d] )*$/i
演示
正則運算式可以分解如下。
/
^ # 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
請注意,我防止連續出現兩個下劃線的方式有一個偶然的副作用,即確保字串中的最后一個字符不是下劃線(免費贈品!)。
uj5u.com熱心網友回復:
您可能正在尋找
^(?!_|\d)(?!.*__)(?!.*_$)\w $
在 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}`);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/429095.html
標籤:javascript 正则表达式 验证 lwc
