【问题标题】:Powershell RegEx: How can I match lines with two matching strings?Powershell RegEx:如何匹配具有两个匹配字符串的行?
【发布时间】:2014-08-29 01:40:53
【问题描述】:

我正在尝试从文本日志文件中提取某些数据并将该数据保存到输出文件中。 文本文件中的数据如下所示:

2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 1 2 3' <more_stuff_I_don't_want_to_EOL>
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 <nonmatching line>
2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 4 5 6' <more_stuff_I_don't_want_to_EOL>

我想创建一个如下所示的输出文件:

2014-08-23 19:05:09 12345 queue1 1 2 3
2014-08-23 19:05:09 12345 queue1 4 5 6

我有两个 RegEx 表达式用于 2 个必要的匹配,当它们单独使用时,它们都可以工作,如下所示:

(^.*?)(?=\b\tMATCH_STRING\b)

返回

2014-08-23 19:05:09
2014-08-23 19:05:09

(?<=@description\=')(?:(?!').)*

返回

12345 queue1 1 2 3
12345 queue1 4 5 6

问题是: 如何将它们放在一起,以便它们匹配行首的日期和行中的引用字符串?

额外问题:对于我正在尝试做的事情,是否有更高效的 RegEx?

谢谢

【问题讨论】:

    标签: regex powershell


    【解决方案1】:
    (\d+-\d+-\d+\s*\d+:\d+:\d+).*?(?=@description).*?=.(\d+)\s*(.*?[\d\s]+)
    

    这个正则表达式给出了你想要的所有组。

    查看演示。

    http://regex101.com/r/lK9iD2/6

    【讨论】:

      【解决方案2】:

      另一种解决方案:

      $matchstring = "MATCH_STRING"
      $pattern = "(.*?)(?:\s*?$([regex]::Escape($matchstring)).*?description=')(.*?)'.*"
      
      @"
      2014-08-23 19:05:09 <nonmatching line>
      2014-08-23 19:05:09 MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 1 2 3' <more_stuff_I_don't_want_to_EOL>
      2014-08-23 19:05:09 <nonmatching line>
      2014-08-23 19:05:09 <nonmatching line>
      2014-08-23 19:05:09MATCH_STRING <stuff_I_don't_want> @description='12345 queue1 4 5 6' <more_stuff_I_don't_want_to_EOL
      "@ -split [environment]::newline |
      Where-Object { $_ -match $pattern } |
      ForEach-Object { $_ -replace $pattern, '$1 $2' }
      
      2014-08-23 19:05:09 12345 queue1 1 2 3
      2014-08-23 19:05:09 12345 queue1 4 5 6
      

      【讨论】:

        【解决方案3】:

        您可以像这样使用正则表达式:

        ^([\d-:\s]{2,}).*?(?<==)'(\d+)(.+?)'
        

        Working demo

        MATCH 1
        1.  [39-59] `2014-08-23 19:05:09 `
        2.  [107-112]   `12345`
        3.  [112-125]   ` queue1 1 2 3`
        MATCH 2
        1.  [238-258]   `2014-08-23 19:05:09 `
        2.  [306-311]   `12345`
        3.  [311-324]   ` queue1 4 5 6`
        

        【讨论】:

          猜你喜欢
          • 2014-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-02
          • 1970-01-01
          • 1970-01-01
          • 2019-12-07
          • 1970-01-01
          相关资源
          最近更新 更多