简体   繁体   中英

Regular expression to get string and number between square brackets - javascript

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

If the string is always in the format something[part0][part1] , use this:

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

When you use the global flag, you just get an array of the matches of the entire regexp, not the capture groups. But in your case you don't seem to need global, you just want to capture two specific elements, so use two capture groups.

Note that capture group numbering starts at 1 -- parts[0] is the match for the entire regep.

just do like this.

var $name = 'event[1][start]';
var parts = $name.match(/\w+/g);
console.log(parts[1] + ' - ' + parts[2]);

You can do this to extract capturing groups:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM