为什么javascript字符串匹配包括undefined [英] Why javascript string match includes undefined

查看:122
本文介绍了为什么javascript字符串匹配包括undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个或多或少像这样使用的正则表达式:

I have a regex that is more or less used like this:

'(801) 555-1234'.match(/^(1[-. ]?)?\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/)

由于某种原因,这将返回

For some reason this returns

["(801) 555-1234", undefined]

如果我将全局标志添加到正则表达式(例如 ... {4} $ / g ),则未定义的值会丢失并且我得到

If I add the global flag to the regex (e.g. ...{4}$/g), the undefined value drops out and I get

["(801) 555-1234"]

如果没有必要,我宁愿不使用g标志(在我看来它不是,因为正则表达式以^开头并以$结尾)。

I'd prefer not to use the g flag if it's not necessary (which it would seem to me it's not, since the regex begins with ^ and ends with $).

PS忽略正则表达式的质量,因为它的目的是匹配电话号码。它可能不太理想,但是来自我维护的代码。大多数情况下,我对^ ... $以及标志的存在/不存在以及未定义的值感兴趣。

P.S. ignore the quality of the regex for it's purpose of matching phone numbers. It may not be ideal, but is from code I'm maintaining. Mostly I'm interested in the ^...$ and the presence/absence of the flag and the undefined value.

为什么 undefined 出现,为什么国旗会有所不同?

Why is undefined showing up, and why does the flag make the difference?

推荐答案

这是一个小组:

/^(1[-. ]?)?

.match (不含 / g 标志)和 .exec 返回组作为数组的一部分。如果该组不匹配,则其值设置为 undefined

.match (without the /g flag) and .exec return groups as part of the array. If the group didn’t match, its value is set to undefined.

获取第一个元素:

'(801) 555-1234'.match(/^(1[-. ]?)?\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/)[0]

如果你真的,真的,真的想要单元素阵列出于某种原因,你可以让它不被捕获:

If you really, really, really want the single-element array for some reason, you can make it non-capturing:

/^(?:1[-. ]?)?

然而,此时,您将此正则表达式锚定到字符串的开头和结尾,并且不提取任何信息。在这种情况下,您似乎真的在寻找 RegExp.prototype.test

However, at that point, you have this regular expression anchored to both the start and end of the string and aren’t extracting any information. In that case, it seems like you’re really looking for RegExp.prototype.test:

var PHONE_NUMBER = /^(1[-. ]?)?\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/;
var isValid = PHONE_NUMBER.test('(801) 555-1234');

这篇关于为什么javascript字符串匹配包括undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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