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

标签 c# asp.net

我有带日期的字符串,想根据日期拆分为单独的字符串

例如:我有这种类型的字符串数据

"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);

任何人都可以建议如何分割这个..

最佳答案

我寻求完整的答案

 static void Main(string[] args)
        {
            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}");
            }

            for (int i = 0; i < matches.Count - 1; i++)
            {
                int start = matches[i].Index;
                int end = matches[i + 1].Index;
                var item = source.Substring(start, end - start);
                Console.WriteLine("---------");
                Console.WriteLine(item);
            }

            var lastitem = source.Substring(matches.Last().Index);
            Console.WriteLine("---------");
            Console.WriteLine(lastitem);
        }

这将输出

---------
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

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

相关文章:

c# - Postman 生成的 RestSharp 代码不起作用

c# - Entity Framework - 使用数据注释的属性的默认值

c# - 创建空数组并添加值导致 "Array index is out of range"

c# - 在同一方法中使用多个等待的效果?

c# - 从后台工作人员登录MyLogger时发生跨线程InvalidOperationException

c# - ffmpeg 要求安装

c# - ASP.NET MVC : No owin. 环境

c# - 将 IN 子句中的多个数字作为参数传递给 Oracle 查询时出现无效数字异常

asp.net - 如何为 html 操作链接提供按钮样式

c# - XSS 是否可以通过 MailAddress 类实现?