javascript正则表达式返回null,试图在括号之间获取文本

Gra*_*ley 4 javascript regex match

试图将"表2"或任何表号(有时2位数)变为变量.知道为什么会这样null吗?

 var productText = '25-08-12 Boat Cruise (Table 2)';
 var rgx = /^\(\)$/;
 var newText = productText.match(rgx);
 alert(newText);
Run Code Online (Sandbox Code Playgroud)

Joã*_*lva 7

请改用以下内容:

var rgx = /\(([^)]+)\)/;
var match = productText.match(rgx);
var newText = match && match[1];
// newText's value will be "Table 2" if there is match; null otherwise
Run Code Online (Sandbox Code Playgroud)

当你有/^\(\)$/,你实际上是在尝试匹配字符串"()",不多也不少.相反,您应该在文本中的任何位置匹配a (,)在捕获组中存储它与下一个之间的所有内容([^)]+),以便稍后可以引用捕获的组match[1].

如果您只想要数字,请使用/\(Table (\d+)\)/.