JavaScript正则表达式-null参数使正则表达式匹配 [英] JavaScript regex - null argument makes the regex match

查看:181
本文介绍了JavaScript正则表达式-null参数使正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个正则表达式以与JavaScript一起使用.测试时,我遇到了一些奇怪的行为,并将其归结为以下内容:

I'm writing a regex to be used with JavaScript. When testing I came across some strange behavior and boiled it down to the following:

/^[a-z]/.test("abc"); // <-- returns true as expected
/^[a-z]/.test(null);  // <-- returns true, but why?

我以为最后一种情况将返回 false ,因为它不符合正则表达式(该值为null,因此不要以该范围内的字符开头).那么,谁能解释我为什么不是这种情况?

I was assuming that the last case was going to return false since it does not meet the regex (the value is null and thus, do no start with a character in the range). So, can anyone explain me why this is not the case?

如果我在C#中执行相同的测试:

If I do the same test in C#:

var regex = new Regex("^[a-z]");
var res = regex.IsMatch(null); // <-- ArgumentNullException

...我得到一个有意义的 ArgumentNullException .因此,我猜想在JavaScript中测试正则表达式时,您必须手动执行 null 检查吗?

... I get an ArgumentNullException which makes sense. So, I guess when testing a regex in JavaScript, you have to manually do a null check?

我试图寻找一种解释,但没有任何运气.

I have tried searching for an explanation, but without any luck.

推荐答案

这是因为 test 转换其参数: null 转换为"null" 字符串.

That's because test converts its argument : null is converted to the "null" string.

您可以在控制台中进行检查:

You can check that in the console :

/^null$/.test(null)

返回 true .

ECMAScript规范中指定了对 ToString(argument)的调用.(另请参见 ToString ).

The call to ToString(argument) is specified in the ECMAScript specification (see also ToString).

这篇关于JavaScript正则表达式-null参数使正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆