如果一组不匹配,如何设置 NULL?

How to set NULL if one group doesn't match?

我有这个正则表达式:

var match  = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(val);
var before = Number(match[1]) + 1;

现在,当没有任何匹配项时,我遇到了这个错误:

Uncaught TypeError: Cannot read property '1' of null

我该如何解决?我想我必须设置 NULL 而不是 match[1].

试试这个:

var before = ( match === null ) ? 1 : match[1]

如果没有找到匹配项,这会将 before 设置为 1,否则它应该 return 正确的匹配项。

你先匹配一下看看有没有。

var m = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(val);
var before = m === null ? 0 : +m[1]+1;
/* notice the Array returned by match can be immediately accessed then
   cast to a number with + in front */