0

I am needing to get the number (1) and the string (start) from this string so I can increment number, the below regex works but still has the [] around the output - anybody have a regex that will remove the []'s as well?

var $name = 'event[1][start]';
var parts = $name.match(/\[(.*?)\]/g);
console.log(parts[0] + ' - ' + parts[1]);
// I wish to do something like this eventually...
// var $newName = 'event[' + ++parts[0] + '][' + parts[1] + ']';

Many thanks

4

3 回答 3

0

就这样做。

var $name = 'event[1][start]';
var parts = $name.match(/\w+/g);
console.log(parts[1] + ' - ' + parts[2]);
于 2013-08-16T01:15:31.550 回答
0

您可以这样做来提取捕获组:

var $name = 'event[1][start]';
var pattern=new RegExp("\\[(.*?)\\]","g");
var parts = pattern.exec($name);
while (parts!=null) {
    console.log(parts[1]);
    parts = pattern.exec($name);
}
于 2013-08-16T01:21:10.700 回答
0

如果字符串始终采用 format something[part0][part1],请使用以下命令:

var parts = $name.match(/.*?\[(.*?)\]\[(.*?)\]/);
console.log(parts[1] + ' - ' + parts[2]);

当您使用该global标志时,您只会获得整个正则表达式的匹配数组,而不是捕获组。但在您的情况下,您似乎不需要全局,您只想捕获两个特定元素,因此使用两个捕获组。

请注意,捕获组编号从 1 开始 -parts[0]是整个 regep 的匹配项。

于 2013-08-16T01:08:47.763 回答