为什么 javascript 字符串匹配包括未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21026134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why javascript string match includes undefined
提问by jinglesthula
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]
If I add the global flag to the regex (e.g. ...{4}$/g
), the undefined value drops out and I get
如果我将全局标志添加到正则表达式(例如...{4}$/g
),未定义的值就会消失,我得到
["(801) 555-1234"]
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 $).
如果没有必要,我宁愿不使用 g 标志(在我看来它不是,因为正则表达式以 ^ 开头并以 $ 结尾)。
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.
PS忽略正则表达式的质量以匹配电话号码。它可能并不理想,但来自我正在维护的代码。大多数情况下,我对 ^...$ 以及标志的存在/不存在和未定义的值感兴趣。
Why is undefined
showing up, and why does the flag make the difference?
为什么undefined
出现,为什么旗帜会产生影响?
回答by Ry-
Here is a group:
这是一组:
/^(1[-. ]?)?
.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
.
.match
(没有/g
标志)并.exec
返回组作为数组的一部分。如果组不匹配,则其值设置为undefined
。
Get the first element:
获取第一个元素:
'(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[-. ]?)?
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
:
但是,此时,您已将此正则表达式锚定到字符串的开头和结尾,并且不会提取任何信息。在这种情况下,您似乎真的在寻找RegExp.prototype.test
:
var PHONE_NUMBER = /^(1[-. ]?)?\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/;
var isValid = PHONE_NUMBER.test('(801) 555-1234');
回答by Pointy
It's because your regex starts with that parenthesized group. The undefined
in the result means that nothing matched that part.
这是因为您的正则表达式以括号中的组开头。将undefined
在结果意味着什么相匹配的那部分。
When you add the "g" suffix, the behavior of the regex code changes a little, so the return value is different. The "g" ("global") suffix causes the routine to return all the matches of the whole regex; the groups are effectively ignored in that case. For example:
添加“g”后缀时,正则表达式代码的行为略有变化,因此返回值不同。“g”(“global”)后缀使例程返回整个正则表达式的所有匹配项;在这种情况下,这些组实际上被忽略了。例如:
"hello world! nice day today!".match(/\w+/g)
would return an array like this:
将返回一个这样的数组:
["hello", "world", "nice", "day", "today"]
回答by Niet the Dark Absol
You have a captured subpattern: (1[-. ]?)?
你有一个捕获的子模式: (1[-. ]?)?
It is optional.
它是可选的。
In this case, the option is to not match it.
在这种情况下,选项是不匹配。
Thus, it is undefined.
因此,它是未定义的。
Try using a non-capturing subpattern: (?:1[-. ]?)?
尝试使用非捕获子模式: (?:1[-. ]?)?
回答by Rakesh KR
In Your Regex (1[-. ]?)?
indicates
在您的正则表达式中(1[-. ]?)?
表示
NODE EXPLANATION
--------------------------------------------------------------------------------
( group and capture to (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
1 '1'
--------------------------------------------------------------------------------
[-. ]? any character of: '-', '.', ' '
(optional (matching the most amount
possible))
--------------------------------------------------------------------------------
)? end of (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in )
And Try (?:1[-. ]?)?
并尝试 (?:1[-. ]?)?
NODE EXPLANATION
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
1 '1'
--------------------------------------------------------------------------------
[-. ]? any character of: '-', '.', ' '
(optional (matching the most amount
possible))
--------------------------------------------------------------------------------
)? end of grouping