JavaScript正则表达式与精确字符串不匹配
在下面的示例中,输出为true。它JavaScript正则表达式与精确字符串不匹配,javascript,regex,match,exact-match,Javascript,Regex,Match,Exact Match,在下面的示例中,输出为true。它cookie而且它也匹配cookie14214我猜这是因为cookie在字符串cookie14214中。我如何在这场比赛中磨练,只获得cookie var patt1=new RegExp(/(biscuit|cookie)/i); document.write(patt1.test("cookie14214")); 这是最好的解决方案吗 var patt1=new RegExp(/(^biscuit$|^cookie$)/i); 是的,或者使用单词边界。请
cookie
而且它也匹配cookie14214
我猜这是因为cookie在字符串cookie14214
中。我如何在这场比赛中磨练,只获得cookie
var patt1=new RegExp(/(biscuit|cookie)/i);
document.write(patt1.test("cookie14214"));
这是最好的解决方案吗
var patt1=new RegExp(/(^biscuit$|^cookie$)/i);
是的,或者使用单词边界。请注意,这将匹配
greatcookies
,但不匹配greatcookies
var patt1=new RegExp(/(\bbiscuit\b|\bcookie\b)/i);
如果您想匹配准确的字符串
cookie
,那么您甚至不需要正则表达式,只需使用=
,因为/^cookie$/i.test
基本上与s.toLowerCase()==“cookie”
这个答案取决于您对cookie
一词周围字符的允许。如果单词严格地单独出现在一行上,则:
var patt1=new RegExp(/^(biscuit|cookie)$/i);
如果要允许符号(空格、
、、
等),但不允许字母数字值,请尝试以下操作:
var patt1=new RegExp(/(?:^|[^\w])(biscuit|cookie)(?:[^\w]|$)/i);
第二个正则表达式,解释如下:
(?: # non-matching group
^ # beginning-of-string
| [^\w] # OR, non-alphanumeric characters
)
(biscuit|cookie) # match desired text/words
(?: # non-matching group
[^\w] # non-alphanumeric characters
| $ # OR, end-of-string
)
你测试过这个吗?我不认为您可以在所需字符串后使用负前瞻。@jbabey是的,用firebug测试过;此外,正则表达式没有使用任何lookahead(正数或负数)。第二个是使用一个不匹配的组,
(?:
),如果你把它与(?!
@jbabey混淆了,那么它是一个很好的使用方法;它的工作方式就像它的名字所暗示的那样-正则表达式也必须匹配该组,但它不会在匹配列表中返回它。因此,返回数组将只包含两个组(第一个是“完整上下文”的匹配,第二个是匹配的单词)。