我需要根据复杂的分隔符拆分字符串

发布于 2024-08-26 22:20:41 字数 245 浏览 1 评论 0原文

在 C# 中,我需要根据特定的字符序列(即“nnnn-nn-nn nn:nn:nn INFO”)将字符串(log4j 日志文件)拆分为数组元素。我目前正在按换行符拆分此日志文件,这很好,除非日志语句本身包含换行符。

我不控制输入(日志文件),因此无法以某种方式转义它们。

似乎我应该能够使用比较器或正则表达式来识别字符串,但 String.Split 没有这样的选项。

我是否坚持自己滚动,或者是否有模式或框架组件可以提供帮助?

In C# I need to split a string (a log4j log file) into array elements based on a particular sequence of characters, namely "nnnn-nn-nn nn:nn:nn INFO". I'm currently splitting this log file up by newlines, which is fine except when the log statements themselves contain newlines.

I don't control the input (the log file) so escaping them somehow is not an option.

It seems like I should be able to use a comparator or a regex to identify the strings, but String.Split does not have an option like that.

Am I stuck rolling my own, or is there a pattern or framework component that can be of help here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

同展鸳鸯锦 2024-09-02 22:20:41

使用 Regex.Split()为了这。

这个正则表达式应该可以工作,但你可能会找到更好的正则表达式:

@"\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d INFO"

Use Regex.Split() for this.

This regex should work but you might find a better one:

@"\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d INFO"
顾北清歌寒 2024-09-02 22:20:41

我最终不得不在某种程度上自行解决这个问题,因为我需要 Regex.Split 所使用的分隔符。

private List<string> splitOnLogDelimiter(string bigString)
{
    Regex r = new Regex("[0-9]{4,4}-[0-9]{2,2}-[0-9]{2,2} [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2} INFO");
    List<string> result = new List<string>();

    //2010-03-26 16:06:38 INFO
    int oldIndex = 0;
    int newIndex = 0;
    foreach (Match m in r.Matches(bigString))
    {
        newIndex = m.NextMatch().Index-1;
        if (newIndex <= 0) break;
        result.Add(bigString.Substring(oldIndex, newIndex - oldIndex));

        oldIndex = newIndex+1;
    }
    return result;


}

I ended up having to roll my own to some extent on this one, because I need the delimiter, which Regex.Split eats.

private List<string> splitOnLogDelimiter(string bigString)
{
    Regex r = new Regex("[0-9]{4,4}-[0-9]{2,2}-[0-9]{2,2} [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2} INFO");
    List<string> result = new List<string>();

    //2010-03-26 16:06:38 INFO
    int oldIndex = 0;
    int newIndex = 0;
    foreach (Match m in r.Matches(bigString))
    {
        newIndex = m.NextMatch().Index-1;
        if (newIndex <= 0) break;
        result.Add(bigString.Substring(oldIndex, newIndex - oldIndex));

        oldIndex = newIndex+1;
    }
    return result;


}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文