简体   繁体   中英

Match number in square brackets and get the remaining string

I have a string like following

value[0]
  1. I want to check if the string contains square brackets.
  2. If yes then get the number which in the above case is 0
  3. Get the rest of the string without brackets and number which in the above case is value
var matches = this.key.match('/[([0-9]+)]/');  // 1 
if (null != matches) {
    var num = matches[1]; // 2
}

How can the third point be accomplished?

You need to remove wrapping quotes, and escape the brackets.

In addition, you can use another catch group to get the string. The 1st catch group should match anything that is not a bracket. Use a fallback array in case no match found, and use destructuring to get the string, and the number. If the string/number are undefined there's no match.

 var key = 'value[0]'; var [, str, number] = key.match(/([^\\[]+)\\[([0-9]+)\\]/) || []; console.log({ str, number });

Use another capture group to get the part of the string before the square brackets.

Also, the regexp shouldn't be quoted.

 var key = 'value[0]' var matches = key.match(/(\\w+)\\[([0-9]+)\\]/); if (null != matches) { var variable = matches[1]; var num = matches[2]; } console.log(`variable = ${variable}, index = ${num}`);

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