【问题标题】:Too many parts after spliting with regexes用正则表达式拆分后的部分太多
【发布时间】:2020-03-18 18:04:47
【问题描述】:

我正在尝试在 powershell 中使用拆分和正则表达式解析一些日志

这是我的代码:

$string = "Starting ChromeDriver 78.0.3904.70Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code. Test 229: Passed Test 260: Failed. Error message: Status: Test case failed.  Steps: Navigate to: PurchReqTableListPage (purchreqpreparedbyme) Use the Quick Filter to find records. For example, filter on the Purchase requisition fION()</StackTrace> </Error>   Playback results: Tests: 2 Passed: 1 Failed: 1"

$string -Split '(Test (\d)+:)'

结果:

Starting ChromeDriver 78.0.3904.70Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Test 229:
9
 Passed
Test 260:
0
 Failed. Error message: Status: Test case failed.  Steps: Navigate to: PurchReqTableListPage (purchreqpreparedbyme) Use the Quick Filter to find records. For example, filter on the Purchase requisition fION()</StackTrace> </Error>   Playback results: Tests: 2 Passed: 1 Failed: 1

预期结果:

Starting ChromeDriver 78.0.3904.70Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Test 229:
 Passed
Test 260:
 Failed. Error message: Status: Test case failed.  Steps: Navigate to: PurchReqTableListPage (purchreqpreparedbyme) Use the Quick Filter to find records. For example, filter on the Purchase requisition fION()</StackTrace> </Error>   Playback results: Tests: 2 Passed: 1 Failed: 1

在这个网站上:https://regexr.com/3c0lf 我尝试了这个正则表达式,捕获的组是:Test 260: 和 Test 229:(这正是我想要的)

我不明白0 和9 来自哪里。

非常感谢

【问题讨论】:

  • 这些是号码的最后几位。 0 来自 260 和 9 来自 229。试试:$string -Split '(Test \d+:)'
  • @RobertMcKee 非常感谢,它正在工作,您介意将其发布为答案并解释为什么我的正则表达式也能捕获一位数字组吗? (所以我可以接受)
  • 完成,但据我所知,您的链接指向错误的正则表达式。

标签: regex powershell split


【解决方案1】:

这些是数字的最后一位。 0 来自 26*0* 和 9 来自 22*9*。 您看到这些是因为您通过在数字周围加上括号创建了一个额外的捕获组。像这样删除它们:

$string -Split '(Test \d+:)

你可能甚至不需要那些括号,只留下

$string -Split 'Test \d+:

【讨论】:

  • 括号允许我将匹配的组保留在拆分结果中
  • 啊...您正在寻找后面的原子正面外观,它会在不滥用捕获组的情况下做同样的事情。
  • 我会用谷歌搜索一下,谢谢提示
  • 试试这个模式:(?&lt;=Test \d+:)
  • 嗯,不,我的日志格式是' [初始化文本] [测试 xxx:] [测试结果] [测试失败时的错误消息] [测试 xxx:] [结果测试] [测试失败时的错误消息] [测试:N 通过:X 失败:Y]'([] 是我想要拆分的方式)
猜你喜欢
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
  • 2014-02-15
相关资源
最近更新 更多