簡體   English   中英

匹配方括號中的數字並得到剩余的字符串

[英]Match number in square brackets and get the remaining string

我有一個像下面這樣的字符串

value[0]
  1. 我想檢查字符串是否包含方括號。
  2. 如果是,則獲取在上述情況下為0
  3. 獲取不帶括號和數字的字符串的其余部分,在上述情況下為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM