簡體   English   中英

捕獲組中的RegExp捕獲組

[英]RegExp capturing group in capturing group

我想捕獲“ http://test.com/1/2 ”中的“ 1”和“ 2”。 這是我的正則表達式/(?:\\/([0-9]+))/g 問題是我只得到["/1", "/2"] 根據http://regex101.com/r/uC2bW5,我必須獲取“ 1”和“ 1”。

我正在JS中運行RegExp。

您有兩種選擇:

  1. RegExp.prototype.exec使用while循環:

     var regex = /(?:\\/([0-9]+))/g, string = "http://test.com/1/2", matches = []; while (match = regex.exec(string)) { matches.push(match[1]); } 
  2. 根據elclanrs的建議使用replace

     var regex = /(?:\\/([0-9]+))/g, string = "http://test.com/1/2", matches = []; string.replace(regex, function() { matches.push(arguments[1]); }); 

在Javascript中,您的“匹配”始終具有索引為0的元素,其中包含整個模式匹配。 因此,在您的情況下,第二個匹配的索引0為/1/2

如果要獲得定義的第一個匹配組(不包含/的匹配組),則可以在索引為1的匹配數組項中找到它。

不能刪除該索引0 ,它與使用?:定義為non-matching的外部匹配組無關?:

想象一下Javascript將您的整個正則表達式包裝在另外一組括號中。

即字符串Hello World和Regex /Hell(o) World/將導致:

[0 => Hello World, 1 => o]

暫無
暫無

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

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