简体   繁体   English

JavaScript Regex与完全字符串不匹配

[英]JavaScript Regex does not match exact string

In the example below the output is true. 在下面的示例中,输出为true。 It cookie and it also matches cookie14214 I'm guessing it's because cookie is in the string cookie14214 . cookie和它也匹配cookie14214我猜它是因为cookie在字符串cookie14214 How do I hone-in this match to only get cookie ? 我如何磨练这场比赛只获得cookie

var patt1=new RegExp(/(biscuit|cookie)/i);
document.write(patt1.test("cookie14214"));

Is this the best solution? 这是最好的解决方案吗?

var patt1=new RegExp(/(^biscuit$|^cookie$)/i);

The answer depends on your allowance of characters surrounding the word cookie . 答案取决于你对cookie一词的限制。 If the word is to appear strictly on a line by itself, then: 如果单词要严格地出现在一行上,那么:

var patt1=new RegExp(/^(biscuit|cookie)$/i);

If you want to allow symbols (spaces, . , , , etc), but not alphanumeric values, try something like: 如果你想允许符号(空格, ., ,等),而不是字母数字值,你可以试试:

var patt1=new RegExp(/(?:^|[^\w])(biscuit|cookie)(?:[^\w]|$)/i);

Second regex, explained: 第二个正则表达式,解释说:

(?:                 # 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
)

Yes, or use word boundaries. 是的,或使用单词边界。 Note that this will match great cookies but not greatcookies . 请注意,这将匹配great cookies但不匹配greatcookies

var patt1=new RegExp(/(\bbiscuit\b|\bcookie\b)/i);

If you want to match the exact string cookie , then you don't even need regular expressions, just use == , since /^cookie$/i.test(s) is basically the same as s.toLowerCase() == "cookie" . 如果你想匹配确切的字符串cookie ,那么你甚至不需要正则表达式,只需使用== ,因为/^cookie$/i.test(s)s.toLowerCase() == "cookie"基本相同s.toLowerCase() == "cookie"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM