我正在尝试扩大我的正则表达式知识,但我不知道为什么以下返回 true:
/[A-Z]{2}/.test("ABC")
// returns true
我明确地将 {2}
放在表达式中,这意味着只有两个大写字母完全匹配。
根据 http://www.regular-expressions.info/repeat.html :
Omitting both the comma and max tells the engine to repeat the token exactly min times.
我在这里误解了什么?
最佳答案
您必须使用 ^
和 $
来锚定正则表达式以指示字符串的开始和结束。
/^[A-Z]{2}$/.test("ABC")
// returns false
您当前的正则表达式匹配字符串的“AB”部分。
关于javascript - 为什么这个正则表达式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5284931/