Regex matches parts of a string, but not whole string

后端 未结 1 1229
忘了有多久
忘了有多久 2021-01-28 08:44

This is the regex I\'m using to validate a string that can contain lowercase and uppercase letters, numbers and dash:

/([a-zA-Z0-9-])+$/

It has

1条回答
  •  闹比i
    闹比i (楼主)
    2021-01-28 09:15

    I would say you need /^([a-zA-Z0-9-])+$/. You want to match the whole string, not just a part, but you're missing the mark for the beginning of the string ^.

    ^ and $ say between the beginning and the end of the string and ([a-zA-Z0-9-])+ says there can be one or more characters a-zA-Z0-9-.

    Your regexp matches everything which contains one or more characters a-zA-Z0-9- before the end of the string no matter what's before.

    You can test your regular expression on regex101.com (very good online tool for regular expression testing with explanation, reference etc.).

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