2013-05-12 104 views
-3

我正在寫一個正則表達式來提取JavaScript中匹配的第二次出現。 我的意圖提取是「attributes_」,位於「root_first_attributes_0_second_」之後。 請參考下面我的代碼片段作爲例子。正則表達式:只捕獲第二次發生

template = "root_first_attributes_0_second_attributes_0_third_attributes_0_third_name" 

my regex 
========== 
var n = template.match(/(attributes[_\]\[]+)\d+/g) 

我的正則表達式的組成不工作我想要的方式,因爲它返回匹配模式的所有出現,這意味着他們三人返回。

任何意見,將不勝感激。

+0

可能是最清晰的解決方案是簡單地拿第二場比賽返回。 – soulcheck 2013-05-12 12:28:04

+1

如果你想要第二個,只需選擇它:'var n = template.match(/(attributes [_ \] \ [] +)\ d +/g)[ – Atle 2013-05-12 12:30:14

+0

]如下所示:'(? (屬性[_ \] \ [] +)\ d +(?:。*?)){2}'? http://www.regex101.com/r/sI0lK5 – 2013-05-12 12:41:33

回答

1

說明

考慮一個正則表達式應該在JavaScript中工作的下面的PowerShell示例(或它爲我做了上http://www.pagecolumn.com/tool/regtest.htm。正則表達式組返回$ 1進行包含在第二個選項的屬性區域值串。我沒有修改的源文本說明,這也將找到屬性子裏面下劃線。

^.*?_0_[^_]*[_](.*?)(_0_|$)

$Matches = @() 
$String = 'root_first_attributes_0_second_Attributes_ToVoteFor_0_third_attributes_0_third_name' 
Write-Host start with 
write-host $String 
Write-Host 
Write-Host found 
([regex]'^.*?_0_[^_]*[_](.*?)(_0_|$)').matches($String) | foreach { 
    write-host "key at $($_.Groups[1].Index) = '$($_.Groups[1].Value)'" 
    } # next match 

息率

開始: root_first_attributes_0_second_Attributes_ToVoteFor_0_third_attributes_0_third_name

發現 鍵31 = 'Attributes_ToVoteFor'

摘要

  • ^從字符串
  • .*?移動的開始通過l字符的東數量達到
  • _0_第一分隔符
  • [^_]*然後通過下一個非下劃線人物移動
  • [_]直到你讀的第一下劃線
  • (.*?)捕獲和
  • (_0_|$)返回之前的所有字符下一個分隔符或字符串結尾

額外信用

要捕獲列表中第X組的屬性字段,您可以修改正則表達式,方法是對非捕獲塊進行非貪婪搜索,然後進行計數。這些都可以在www.pcreck.com/JavaScript/advanced

  • ^(?:.*?_0_){0}[^_]*[_](.*?)(?=_0_|$)測試匹配first_attributes
  • ^(?:.*?_0_){1}[^_]*[_](.*?)(?=_0_|$)匹配Attributes_ToVoteFor
  • ^(?:.*?_0_){2}[^_]*[_](.*?)(?=_0_|$)匹配attributes
  • ^(?:.*?_0_){3}[^_]*[_](.*?)(?=_0_|$)匹配name