简体   繁体   English

匹配方括号中的数字并得到剩余的字符串

[英]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如果是,则获取在上述情况下为0
  3. Get the rest of the string without brackets and number which in the above case is value获取不带括号和数字的字符串的其余部分,在上述情况下为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.此外,您可以使用另一个 catch 组来获取字符串。 The 1st catch group should match anything that is not a bracket.第一个 catch 组应该匹配任何不是括号的东西。 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.如果字符串/数字undefined则没有匹配项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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