Search code examples
javascriptregexregex-negationregex-groupregex-greedy

RegEx for matching strings not started with a number passing alphanumeric


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]

Solution

  • 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]+
    

    DEMO

    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
    

    Test

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

    RegEx Circuit

    jex.im visualizes regular expressions.

    enter image description here

    enter image description here