Regular Expression for alphanumeric and underscores

前端 未结 20 759
北荒
北荒 2020-11-22 10:01

I would like to have a regular expression that checks if a string contains only upper and lowercase letters, numbers, and underscores.

相关标签:
20条回答
  • 2020-11-22 11:02

    You want to check that each character matches your requirements, which is why we use:

    [A-Za-z0-9_]
    

    And you can even use the shorthand version:

    \w
    

    Which is equivalent (in some regex flavors, so make sure you check before you use it). Then to indicate that the entire string must match, you use:

    ^
    

    To indicate the string must start with that character, then use

    $
    

    To indicate the string must end with that character. Then use

    \w+ or \w*
    

    To indicate "1 or more", or "0 or more". Putting it all together, we have:

    ^\w*$
    
    0 讨论(0)
  • 2020-11-22 11:02

    This works for me, found this in the O'Reilly's "Mastering Regular Expressions":

    /^\w+$/
    

    Explanation:

    • ^ asserts position at start of the string
      • \w+ matches any word character (equal to [a-zA-Z0-9_])
      • "+" Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    • $ asserts position at the end of the string

    Verify yourself:

    const regex = /^\w+$/;
    const str = `nut_cracker_12`;
    let m;
    
    if ((m = regex.exec(str)) !== null) {
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    0 讨论(0)
提交回复
热议问题