2017-08-07 91 views
0

我试图根据下面的代码提取正则表达式字符串,它的工作正常。按照以下脚本,它将文本中的字符串提取为“45 \ 345 \ 54”,如\ 345 \。Powershell正则表达式提取concat文本

$input_path = "E:\DOC\all.txt" 
$output_file = "E:\DOC\all-pts.txt" 
$regex1 = ‘[ \b\t\n\r]+\\+[A-Z0-9_-]+\\$’ 
select-string -Path $input_path -Pattern $regex1 -AllMatches | % { 
$_.Matches } | % { $_.Value } > $output_file 

但是,当我想提取一个多正则表达式字符串CONCAT都使用if语句按照下面的例子我不能够做正则表达式的结果。不知道我在这里犯了什么错误。我刚接触PowerShell。

输入文件(全部.txt)

temp1.txt:未找到文件\某某\找不到\ 123 \
temp2.​​txt:文\ ABC \这里
TEMP2 .TXT:NUM \ 999 \是\ FIRST \

输出文件(全pts.txt)

temp1.txt \ XYZ \
temp1.txt \ 123 \
temp2.​​txt \ ABC \
temp2.​​txt \ 999 \
temp2.​​txt \ FIRST \

$input_path = "E:\DOC\all.txt" 
$output_file = "E:\DOC\all-pts.txt" 
(Get-Content "$input_path") | ForEach-Object 
{if($_ -like ‘[ \b\t\n\r]+\\+[A-Z0-9_-]+\\$’) 

     { 
      $regex1 = ‘[ \b\t\n\r]+\\+[A-Z0-9_-]+\\$’ 
      $regex2 = ‘[ A-Z0-9_-]+\.txt$’ 
      select-string -Path $input_path -Pattern $regex1 -AllMatches | % 
      { $_.Matches } | % { $_.Value } > $output_file 
      select-string -Path $input_path -Pattern $regex2 -AllMatches | % 
      { $_.Matches } | % { $_.Value } > $output_file 
      } 
     } 
+0

'-like'为通配符(例如''/'*'?)。你想使用'-match'或'-cmatch'区分大小写正则表达式 – TheIncorrigible1

+0

问题是我不能连接两个正则表达式结果在同一行中作为每个输出文件。 – Arjun

+0

为什么不结合正则表达式呢? ''[\ b \ t \ n \ r] + \\ + [A-Z0-9 _-] + \\ $ | [A-Z0-9 _-] + \。txt $'' –

回答

1

我不喜欢我的两个RE没有通用的解决方案。
它得到一个或两个值反映在反斜杠中。

$input_path = ".\all.txt" 
$output_file = ".\all-pts.txt" 

$RE1 = "(?<Pat1>\\[^\\]+\\)" 
$RE2 = "(?<Pat1>\\[^\\]+\\)[^\\]+(?<Pat2>\\[^\\]+\\)" 

Get-Content $input_path | ForEach-Object { 
    $Line = $_ -split(':') 
    If ($Line[1] -Match $RE2){ 
     "{0} {1}" -f $line[0],$Matches.Pat1 
     "{0} {1}" -f $line[0],$Matches.Pat2 
    } ElseIf ($Line[1] -Match $RE1) { 
     "{0} {1}" -f $line[0],$Matches.Pat1 
    } 
} | Set-Content $output_file 

示例输出:

> gc .\all-pts.txt 
temp1.txt \xyz\ 
temp1.txt \123\ 
temp2.txt \ABC\ 
temp2.txt \999\ 
temp2.txt \FIRST\