I have a requirement in javascript to write a regex for the following condition
The Custom Metadata Record MasterLabel field can only contain underscores and alphanumeric characters. It must be unique, begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.
If we leave out the unique part since we have to check it with the system records i need a regex for testing the other conditions mentioned above.
Here is an expression ive built so far but it doesnt seem to work. I am new to the regular expressions so any help would be appreciated.
/^[a-zA-Z]([a-zA-Z0-9][^ ][^__])[^_]*$/
CodePudding user response:
You might be looking for
^(?!_)(?!.*__)(?!.*_$)\w $
In JavaScript
:
const regex = /^(?!_)(?!.*__)(?!.*_$)\w $/gm;
const str = `_
A
abcd
_
123
some_spaces
not_any_spaces__
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}`);
});
}
CodePudding user response:
The string has all the required properties if and only if it matches the following regular expression:
/^[a-z][a-z\d]*(?:_[a-z\d] )*$/i
The regular expression can be broken down as follows.
/
^ # match beginning of string
[a-z] # match a letter
[a-z\d]* # match one or more alphas numeric characters
(?: # begin non-capture group
_ # match an underscore
[a-z\d] # match one or more alphas numeric 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
Notice that the way I prevent the presence of two underscores in a row has the fortuitous side-effect of ensuring that the last character in the string is not an underscore (a freebie!).