var name ='John Rock';
alert((/^John|Steve$/i).test(name));
此代码提醒 true
,因为没有使用精确的数学运算,但必须使用。
对于 John
和 joHn
应该返回 true
(大小写匹配关闭)。但不适用于John 12
或mahjohng
。
代码中有|
,我们应该保留它。
如何修复这个正则表达式?
最佳答案
如果您的目标是完全匹配John
或Steve
,您想在其中放置一个组:
alert(/^(?:John|Steve)$/i.text(name));
另请注意 i
不区分大小写。 (半个多小时前,当 Beat Richartz 指出问题时,我确实在 my answer to your other question 中指出了这一点。)
关于javascript - 使用正则表达式精确匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15068232/