2017-03-05 63 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