Regular Expression for alphanumeric and underscores

前端 未结 20 1016
北荒
北荒 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

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

提交回复
热议问题