Regular expressions search for a pattern within the search string. This means that if the regex matches starting from anywhere, and ending anywhere, then it is considered valid. In the examples given:
2014-11-123456
, 12342014-11-12
and a1234-56-78z
all match the regular expression somewhere within them.
This is normal and expected behaviour. In your result set, you will have a total of four elements:
[0]: 2014-11-12 (whole match)
[1]: 2014 (first subpattern)
[2]: 11 (second subpattern)
[3]: 12 (third subpattern)
If you want to verify that the pattern matches your entire string, and only that string, you must anchor your regex using ^
(start of string) and $
(end of string). Your regex will become:
/^(d{4})-(d{2})-(d{2})$/
This will prevent any of your given examples from matching, because they do not match the start and end at the beginning and end of the string correspondingly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…