Regex Letters, Numbers, Dashes, and Underscores

前端 未结 4 1733
盖世英雄少女心
盖世英雄少女心 2020-12-02 19:47

Im not sure how I can achieve this match expression. Currently I am using,

([A-Za-z0-9-]+)

...which matches letters and numbers. I would

相关标签:
4条回答
  • 2020-12-02 20:19

    Your expression should already match dashes, because the final - will not be interpreted as a range operator (since the range has no end). To add underscores as well, try:

    ([A-Za-z0-9_-]+)
    
    0 讨论(0)
  • 2020-12-02 20:22

    Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.

    ([A-Za-z0-9\-\_]+)
    
    0 讨论(0)
  • 2020-12-02 20:27

    Depending on your regex variant, you might be able to do simply this:

    ([\w-]+)
    

    Also, you probably don't need the parentheses unless this is part of a larger expression.

    0 讨论(0)
  • 2020-12-02 20:28

    You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

    If you are using a POSIX variant you can opt to use:

    ([[:alnum:]\-_]+)

    But a since you are including the underscore I would simply use:

    ([\w\-]+)

    (works in all variants)

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