Regex to include alphanumeric and _

前端 未结 2 1996
隐瞒了意图╮
隐瞒了意图╮ 2021-01-23 06:30

I\'m trying to create a regular expression to match alphanumeric characters and the underscore _. This is my regex: \"\\w_*[^-$\\s\\]\" and my impressi

2条回答
  •  后悔当初
    2021-01-23 07:22

    Regular expressions are read as patterns which actually match characters in a string, left to right, so your pattern actually matches an alphanumeric, THEN an underscore (0 or more), THEN at least one character that is not a hyphen, dollar, or whitespace.

    Since you're trying to alternate on character types, just use a character class to show what characters you're allowing:

    [\w_]
    

    This checks that ANY part of the string matches it, so let's anchor it to the beginning and and of the string:

    ^[\w_]$
    

    And now we see that the character class lacks a quantifier, so we are matching on exactly ONE character. We can fix that using + (if you want one or more characters, no empty strings) or * (if you want to allow empty strings). I'll use + here.

    ^[\w_]+$
    

    As it turns out, the \w character class already includes the underscore, so we can remove the redundant underscore from the pattern:

    ^[\w]+$
    

    And now we have only one character in the character class, so we no longer need the character class brackets at all:

    ^\w+$
    

    And that's all you need, unless I'm missing something about your requirements.

提交回复
热议问题