gpt4 book ai didi

javascript - 正则表达式解释

转载 作者:行者123 更新时间:2023-11-30 08:17:02 26 4
gpt4 key购买 nike

我正在查看 tumblr 书签中的代码,很好奇下面的代码做了什么。

try{
if(!/^(.*\.)?tumblr[^.]*$/.test(l.host))
throw(0);
tstbklt();
}

谁能告诉我 if 行正在测试什么?我已尝试解码正则表达式,但未能成功。

最佳答案

最初排除正则表达式的细节,这段代码是:

if ( ! /.../.test(l.host) )

“如果不是 regex.matches(l.host)”或“如果 l.host 不匹配这个正则表达式”

因此,正则表达式必须正确描述 l.host 文本的内容才能使条件失败,从而避免抛出错误。

关于正则表达式本身:

^(.*\.)?tumblr[^.]*$

这是检查 tumblr 是否存在,但仅在可能存在的任何以 . 结尾的字符串之后:

^       # start of line
( # begin capturing group 1
.* # match any (non-newline) character, as many times as possible, but zero allowed
\. # match a literal .
) # end capturing group 1
? # make whole preceeding item optional
tumblr # match literal text tumblr
[^.]* # match any non . character, as many times as possible, but zero allowed
$ # match end of line


I thought it was testing to see if the host was tumblr

是的,看起来它可能是为了检查它,但如果是这样,那就是错误的方法。
为此,第一位应该是 ^(?:[\w-]+\.)? 来捕获字母数字子域(?: 是非-捕获组,[\w-]+ 至少是 1 个字母数字、下划线或连字符),最后一位应该是 \.(?:com|net|org)$ 或者可能像 (?:\.[a-zA-Z]+)+$ 取决于 tld 部分可能需要的灵 active 。

关于javascript - 正则表达式解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1657224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com