簡體   English   中英

JS:如何在同一個字符串中多次匹配一個捕獲組?

[英]JS: How to match one capture group multiple times in the same string?

情況

我有一個字符串,我想多次匹配相同的捕獲組。 我需要能夠得到兩場比賽。

示例代碼

var curly = new RegExp("{([a-z0-9]+)}", "gi");
var stringTest = "This is a {test} of my {pattern}";

var matched = curly.exec(stringTest);
console.log(matched);

問題

現在,它只顯示第一場比賽,而不是第二場比賽。

JSFiddle鏈接

http://jsfiddle.net/npp8jg39/

嘗試這個:

  var curly = /{([a-z0-9]+)}/gi, stringTest = "This is a {test} of my {pattern}", matched; while(matched = curly.exec(stringTest)) console.log(matched); 

如果要處理多個結果,則必須在while循環中使用exec方法。 請參閱MDN文檔

JavaScript中的字符串有一個match方法 - 您可以使用它來匹配正則表達式的所有實例,作為數組返回:

stringTest.match(curly);

這將返回一系列匹配:

> ["{test}", "{pattern}"]

要拉出內部值,可以使用substr

var arr = stringTest.match(curly);

arr[0] = arr[0].substr(1, arr[0].length - 2);
> "test"

或者轉換整個數組:

for (var i = 0; i < arr.length; i++)
    arr[i] = arr[i].substr(1, arr[i].length - 2);
> ["test", "pattern"]

通常這是通過RegExp.exec方法完成的,但是你知道它是錯綜復雜的。 每次我需要使用它時,我必須抬頭記住這個有狀態的操作。 這就像你需要一個州monad或者什么:)

無論如何。 在最近的JS引擎中,有一個String.matchAll()通過返回一個迭代器對象以一種非常理智的方式做同樣的事情。

 var curly = new RegExp("{([a-z0-9]+)}", "gi"); var stringTest = "This is a {test} of my {pattern}"; var matches = [...stringTest.matchAll(curly)]; console.log(matches); 

如果您只需要捕獲組,則只需映射上面的結果。 我們這次使用Array.from()

 var curly = new RegExp("{([a-z0-9]+)}", "gi"); var stringTest = "This is a {test} of my {pattern}"; var matches = Array.from(stringTest.matchAll(curly), m => m[1]); console.log(matches); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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