Powershell在正则表达式匹配组的末尾添加CR

时间:2019-01-18 23:40:00

标签: regex powershell

我在正则表达式匹配和“,”之间得到一个CR。发生了什么事?

$r_date ='ExposeDateTime=([\w /:]{18,23})'   
$v2 = (Select-String -InputObject $_ -Pattern $r_date | ForEach-Object {$_.Matches.Groups[1].Value}) + ',';

输出示例:

  

9/25/2018 8:45:19 AM [CR],

原始字符串:

ExposeDateTime=9/25/2018 8:45:19 AM
Error=Dap
PostKvp=106
PostMa=400
PostTime=7.2
PostMas=2.88
PostDap=0

2 个答案:

答案 0 :(得分:0)

尝试一下:

$original = @"
ExposeDateTime=9/25/2018 8:45:19 AM
Error=Dap
PostKvp=106
PostMa=400
PostTime=7.2
PostMas=2.88
PostDap=0
"@

$r_date ='ExposeDateTime=([\d\s/:]+(?:(?:A|P)M)?)'   
$v2 = (Select-String -InputObject $original -Pattern $r_date | ForEach-Object {$_.Matches.Groups[1].Value}) -join ','

正则表达式详细信息:

ExposeDateTime=    Match the characters “ExposeDateTime=” literally
(                  Match the regular expression below and capture its match into backreference number 1
   [\d\s/:]        Match a single character present in the list below
                   A single digit 0..9
                   A whitespace character (spaces, tabs, line breaks, etc.)
                   One of the characters “/:”
      +            Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   (?:             Match the regular expression below
      (?:          Match the regular expression below
                   Match either the regular expression below (attempting the next alternative only if this one fails)
            A      Match the character “A” literally
         |         Or match regular expression number 2 below (the entire group fails if this one fails to match)
            P      Match the character “P” literally
      )
      M            Match the character “M” literally
   )?              Between zero and one times, as many times as possible, giving back as needed (greedy)

答案 1 :(得分:0)

如果您的输入是存储在$Original中的多行字符串,则此简单得多的正则表达式似乎可以完成任务。 [ grin ]它使用命名的捕获组和multiline正则表达式标志来捕获字符串之后 ExposedDateTime=之前下一行结束。

$Original -match '(?m)ExposeDateTime=(?<Date>.+)$'
$Matches.Date

输出...

9/25/2018 8:45:19 AM