问题
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
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?
My machine is a PC running Arch Linux x86_64. The code is being executed within the scratchpad of firefox 32.0.3.
Thanks for your interest.
回答1:
If somestring.match()
finds no match, then it returns null
.
And, null[0]
throws an exception.
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.
A safer way to code is:
var matches = somestring.match(/some regex/);
if (matches) {
// do something here with matches[0]
}
回答2:
If you want to do it in one statement (and there's no particularly good reason why that is a good idea, see jfriend000's answer), then:
var firstMatchOrFalse = /pattern/.test(somestring) && somestring.match(/pattern/)[0];
and if you only want the first match, why the g flag?
来源:https://stackoverflow.com/questions/26415011/why-does-string-match-0-throws-an-exception