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



我在正则表达式匹配和","之间得到了一个CR。这是怎么回事?

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

输出示例:

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

原始字符串:

ExposeDateTime=9/25/2018 8:45:19 AM
Error=Dap
PostKvp=106
PostMa=400
PostTime=7.2
PostMas=2.88
PostDap=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=([ds/:]+(?:(?: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
   [ds/:]        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)

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

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

输出。。。

9/25/2018 8:45:19 AM

最新更新