I am looking for a regex that only accepts numbers and letters and the first character cannot start with a number.
I found an OK solution that doesn't work all the time by doing:
export const cannotBeginWithAdigit= new RegExp("/^d/");
export const canOnlyContainNumsbersAndDigits = new RegExp('/[,"/\\[]:|<>+=.;?*]/g');
I place the regex between an || to test the first one then the second one.
Other that doesn't work:
^d{1}[0-9a-zA-Z]
Here, we can start (^
) our expression with a not-start-with digits ([^\d]
) followed by a list of our desired chars:
^[^\d][A-Za-z0-9]+
Then, we can also add additional boundaries. For example, anubhava's advice in the comment is good by adding an end char and using i
flag:
/^[a-z][a-z\d]*$/i
const regex = /^[^\d][A-Za-z0-9]+/gm;
const str = `123abc
abc123abc
`;
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(`Found match, group ${groupIndex}: ${match}`);
});
}
jex.im visualizes regular expressions.