gpt4 book ai didi

c# - 正则表达式拆分模式多行

转载 作者:行者123 更新时间:2023-11-30 22:58:03 25 4
gpt4 key购买 nike

我需要从txt文件中读取一些日志数据并进行相应的拆分。
我的示例文件看起来像这样:

11:03:04.234 DEBUG event occurred  
11:03:05.345 INFO another event occurred
11:03:06.222 ERROR notice that this event
occupies multiple lines
as errors can be from multiple sources
and I have no control over this
11:04:07.222 INFO fourth event has happened

我决定不使用 StreamReader,因为它看起来是最有效的方法。我使用 StreamReaderReadToEnd() 方法读取文件的所有内容,并收到一个大字符串。然后,我尝试使用 Regex 来拆分字符串。到目前为止,我能够想出的正则表达式模式如下所示:
([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0- 9].*).
它工作得很好,当然,直到 Regex 解析多行事件。
我用 this tool测试我的模式。

最佳答案

你可以使用

Regex.Split(s, @"(?m)^(?!\A)(?=\d{2}:\d{2}:\d{2}\.\d{3})")

参见 regex demo

详情

  • (?m)^ - 一行的开始
  • (?!\A) - 但不是字符串的开头
  • (?=\d{2}:\d{2}:\d{2}\.\d{3}) - 后跟 2 位数字,: , 2 digits, :, 2 digits, . 和 3 digits.

结果:

enter image description here

关于c# - 正则表达式拆分模式多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53253484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com