为什么 string.match(...)[0] 会抛出异常? [英] Why does string.match(...)[0] throws an exception?

查看:71
本文介绍了为什么 string.match(...)[0] 会抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个语句中从字符串中提取第一次出现的正则表达式模式,以使我的代码看起来更简洁.这就是我想要做的:

I'm trying to pull the first occurence of a regex pattern from a string all in one statement to make my code look cleaner. This is what I want to do:

var matchedString = somestring.match(/some regex/g)[0];

我希望这是合法的,但它会引发异常:

I would expect this to be legal but it throws an exception:

Exception: somestring.match(...) is null

似乎 JS 试图在匹配结束之前索引数组,因为数组确实提供了至少一个匹配,所以我不希望它为空.

It seems like JS is trying to index the array before match is finsihed, as the array does provide atleast one match, so I don't expect it to be null.

我想了解为什么会发生这种情况.这可能是一个错误吗?

I would like some insight in why it happens. Could it be a bug?

我的机器是一台运行 Arch Linux x86_64 的 PC.代码在firefox 32.0.3的scratchpad中执行.

My machine is a PC running Arch Linux x86_64. The code is being executed within the scratchpad of firefox 32.0.3.

感谢您的关注.

推荐答案

如果 somestring.match() 没有找到匹配项,则返回 null.

If somestring.match() finds no match, then it returns null.

而且,null[0] 抛出异常.

由于您收到了这个确切的异常,因此在内容中找不到您的正则表达式.以这种方式在匹配选项上使用 g 标志时要非常小心,因为当您在正则表达式中指定子匹配时,它并不总是按照您的预期执行.由于看起来您只是想要第一个匹配项,因此您可能应该删除 g 选项.

Since you are getting this exact exception, your regex is not being found in the content. Be very careful using the g flag on a match option in this way as it does not always do what you expect when you have submatches specified in the regex. Since it looks like you just want the first match anyway, you should probably remove the g option.

更安全的编码方式是:

var matches = somestring.match(/some regex/);
if (matches) {
    // do something here with matches[0]
}

这篇关于为什么 string.match(...)[0] 会抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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