Regex to include alphanumeric and _

前端 未结 2 1998
隐瞒了意图╮
隐瞒了意图╮ 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:19

    Yes, you are semi-correct if the closing bracket was not escaped and you edited your regex a bit. Also the token \w matches underscore, so you do not need to repeat this character. Your regular expression says:

    \w         # word characters (a-z, A-Z, 0-9, _)
    _*         # '_' (0 or more times)
    [^-$\s]    # any character except: '-', '$', whitespace (\n, \r, \t, \f, and " ")
    

    You could simply write your entire regex as follows to match word characters:

    \w+        # word characters ( a-z, A-Z, 0-9, _ ) (1 or more times)
    

    If you want to match an entire string, be sure to anchor your expression.

    ^\w+$
    

    Explanation:

    ^          # the beginning of the string
     \w+       #   word characters ( a-z, A-Z, 0-9, _ ) (1 or more times)
    $          # before an optional \n, and the end of the string
    

提交回复
热议问题