gpt4 book ai didi

c# - 如何在c#中根据日期拆分字符串数据

转载 作者:行者123 更新时间:2023-12-04 07:34:31 25 4
gpt4 key购买 nike

我有带日期的字符串,想根据日期拆分为单独的字符串
例如:我有这种类型的字符串数据

"21/04/21, 1:54 pm - Person1: Really a very useful website to know the products.\n\nhttps://www.google.com\n21/04/21, 2:08 pm - Person2: this is second text\n21/04/21, 2:53 pm - Person3: Really a very useful website for question and answers.\n\nhttps://www.stackoverflow.com\n"
我想根据日期拆分它
"21/04/21, 1:54 pm - Person1: Really a very useful website to know the products.\n\nhttps://www.google.com"
"21/04/21, 2:08 pm - Person2: this is second text"
"22/04/21, 2:53 pm - Person3: Really a very useful website for question and answers.\n\nhttps://www.stackoverflow.com\n"
我试过下面的代码,但它拆分为换行符而不是日期
string[] lines = text.Split(new[] { "\r\n", "\r", "\n" },StringSplitOptions.None);
谁能建议如何拆分这个..

最佳答案

正则表达式可能是您的解决方案。

  • 使用正则表达式查找日期模式位置:^[0-9]{2}/[0-9]{2}/[0-9]{2}, [0-9]:[0-9]{2} (pm|am)
  • 使用日期位置拆分字符串

  • 像这样:
    Regex regex = new Regex("^[0-9]{2}/[0-9]{2}/[0-9]{2}, [0-9]:[0-9]{2} (pm|am)", RegexOptions.Multiline);
    var source = @"
    21/04/21, 1:54 pm - Person1: Really a very useful website to know the products.

    https://www.google.com
    21/04/21, 2:08 pm - Person2: this is second text
    21/04/21, 2:53 pm - Person3: Really a very useful website for question and answers.
    https://www.stackoverflow.com";
    var matches = regex.Matches(source);
    foreach (Match match in matches)
    {
    var g = match.Groups[0];
    Console.WriteLine($"{g.Index} : {g.Value}");
    }
    将产生以下输出,这是我的第一步建议:
    2 : 21/04/21, 1:54 pm
    109 : 21/04/21, 2:08 pm
    159 : 21/04/21, 2:53 pm
    我让你用sring splitting完成它

    关于c# - 如何在c#中根据日期拆分字符串数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67800999/

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