2017-03-05 60 views
-1

我是Powershell的新手,嘗試使用RegEx解析多個字符串(非分隔符)。默認的RegEx輸出使用$匹配,所以試圖保存來自第一個字符串,第二個字符串,第三個字符串等的值。所以我可以稍後使用「解析」值。使用PowerShell輸出多個RegEx匹配到另一個陣列

我想不出如何運行並將多行輸出保存到新數組中,以便日後檢索值?

  1. 設置正則表達式匹配字符串
  2. 設置1對多$字符串變量
  3. 集1個$總可變結合許多$字符串變量形成步驟2
  4. 的foreach變量IN $總,運行正則表達式解析字符串到單獨的值

#Work 
$regex = "([A-Z]*\..*\.[A-Z]?) (?:\s*) ([A-Za-z]{3}\s\d{1,2}, \d{4} \d{2}:\d{2}:\d{2}) ([A-Za-z]{3}\s\d{1,2}, \d{4} \d{2}:\d{2}:\d{2}) ([A-Z]{2}) (\d*)/(\d) (\d)" 

$string01 = "DEV.This_Is_Command_JobA.C    Jun 7, 2016 07:33:35 Jun 7, 2016 07:59:22 SU 84534137/1 0" 
$string02 = "DEV.This_Is_Command_JobB.C    Jun 8, 2016 08:33:35 Jun 8, 2016 08:59:22 SU 84534138/1 0" 
$string03 = "DEV.This_Is_Command_JobC.C    Jun 9, 2016 09:33:35 Jun 9, 2016 09:59:22 SU 84534139/1 0"  

$total = $string01,$string02,$string03 

Foreach ($_ in $total) 
{ 
    $_ -match $regex 
} 

#check work 
$matches 

所需的輸出:

 

    7  0       
    6  1       
    5  84534139      
    4  SU       
    3  Jun 7, 2016 07:59:22   
    2  Jun 7, 2016 07:33:35   
    1  DEV.This_Is_Command_JobA.C 
    0  DEV.This_Is_Command_JobA.C 

    7  0       
    6  1       
    5  84534139      
    4  SU       
    3  Jun 8, 2016 08:59:22   
    2  Jun 8, 2016 08:33:35   
    1  DEV.This_Is_Command_JobB.C 
    0  DEV.This_Is_Command_JobB.C 

    7  0       
    6  1       
    5  84534139      
    4  SU       
    3  Jun 9, 2016 09:59:22   
    2  Jun 9, 2016 09:33:35   
    1  DEV.This_Is_Command_JobC.C 
    0  DEV.This_Is_Command_JobC.C 

    So I can retrieve values such as an example: 
    $matchesA[0-7] 
    $matchesB[0-7] 
    $matchesC[0-7] 

+0

那麼最新的問題? – 4c74356b41

+0

'$ Result = @($ total |%{[Regex] :: Match($ _,$ regex)})' – PetSerAl

+0

請清楚地突出顯示主要問題,不是很清楚嗎? – SACn

回答

0
  • 聲明字符串作爲數組:

    $results = foreach ($s in $strings) { 
        $s -match $regex >$null; 
        ,$matches 
    } 
    

    或​​爲了簡潔:

    $strings = @(
        "................." 
        "................." 
        "................." 
    ) 
    

    然後使用foreach循環收集$matches

    現在,您可以針對$ strings [0]等訪問$ results [0]作爲$ results [0] [0],$ results [0] [1]。

  • 聲明字符串作爲一個哈希表中使用的名稱:

    $strings = @{ 
        A="................." 
        B="................." 
        C="................." 
    } 
    
    $results = @{} 
    foreach ($item in $strings.GetEnumerator()) { 
        $item.value -match $regex >$null 
        $results[$item.name] = $matches 
    } 
    

    現在您可以訪問$ results.A爲$ results.A [0],$ results.A [ 1]爲$ strings.A等等。

注:

  • $s -match $regex填充內置$matches哈希表的結果對當前字符串,並返回一個布爾值$ true或$ false,我們不會在需要輸出所以>$null丟棄它。
  • ,$matches@($matches)的簡寫形式,用於處理空$匹配的情況,並將其作爲$results中的一個空元素輸出,否則將被跳過,從而減少$ results中元素的數量。
+0

這正是我正在尋找的。謝謝! – SFNicoya