C# 字符串正则 提取时间 ,时间格式 2023/7/7 10:27:55
时间: 2024-04-07 18:33:29 浏览: 9
你可以使用正则表达式来提取时间字符串。对于时间格式为"2023/7/7 10:27:55",你可以使用以下的C#代码来提取时间:
```csharp
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "2023/7/7 10:27:55";
string pattern = @"\b\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{2}:\d{2}\b";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
string timeString = match.Value;
DateTime time = DateTime.ParseExact(timeString, "yyyy/M/d H:mm:ss", null);
Console.WriteLine(time);
}
}
}
```
以上代码中,我们使用了`\b\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{2}:\d{2}\b`正则表达式来匹配时间字符串。然后,我们使用`DateTime.ParseExact`方法将匹配到的时间字符串转换为`DateTime`类型的时间对象。最后,我们打印出了提取到的时间。
请注意,上述代码假设输入的时间格式始终符合"yyyy/M/d H:mm:ss"的模式。如果输入的时间格式可能有变化,你需要根据实际情况进行调整。