![](/img/trans.png)
[英]Regular expression to get string and number between square brackets - javascript
[英]Match number in square brackets and get the remaining string
我有一個像下面這樣的字符串
value[0]
0
value
var matches = this.key.match('/[([0-9]+)]/'); // 1
if (null != matches) {
var num = matches[1]; // 2
}
第三點如何實現?
您需要刪除包裝引號,並轉義括號。
此外,您可以使用另一個 catch 組來獲取字符串。 第一個 catch 組應該匹配任何不是括號的東西。 如果找不到匹配項,請使用回退數組,並使用解構來獲取字符串和數字。 如果字符串/數字undefined
則沒有匹配項。
var key = 'value[0]'; var [, str, number] = key.match(/([^\\[]+)\\[([0-9]+)\\]/) || []; console.log({ str, number });
使用另一個捕獲組來獲取方括號之前的字符串部分。
此外,不應引用正則表達式。
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.