Regex matches parts of a string, but not whole string

耗尽温柔 提交于 2020-07-31 04:21:32

问题


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 the following results:

  • abd - matches
  • abcd- - matches
  • abcd0 - matches
  • abcd0- - matches
  • abc@ - doesn't match (correct)
  • abc@efg - matches (incorrect, it shouldn't)

What am I doing wrong?


回答1:


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.).



来源:https://stackoverflow.com/questions/36176971/regex-matches-parts-of-a-string-but-not-whole-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!