问题
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
- matchesabcd-
- matchesabcd0
- matchesabcd0-
- matchesabc@
- 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