c# - 如何从字符串变量中提取 2 个日期?

标签 c# regex

我有一个包含两个日期的字符串。我查看了 .Split 和 .Substring 函数。不确定我是否走的是最有效的路线。有没有一种干净的方法从字符串中提取日期?

string test = "Hello World.  Random date1 is 12/10/2010. Now 4 days later is 12/14/2010." 

最佳答案

如果日期格式不会改变,你可以这样做:

private static readonly Regex dateRegex = new Regex(@"\d{1,2}/\d{1,2}/\d{4}");

public static IEnumerable<string> ExtractDates(string str)
{
    return dateRegex.Matches(str).Cast<Match>().Select(match => match.Value);
}

然后像这样使用它:

foreach (var dateString in ExtractDates("...")) {
    // ...
}

针对您的示例字符串进行了测试和工作。

关于c# - 如何从字符串变量中提取 2 个日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4370984/

相关文章:

c# - 将 int[] 连接到相同大小的 string[]

c# - 分析音频以自动创建吉他英雄关卡

c# - 使用 asp.net MVC 与 Google 重定向 URI

c++ - 正则表达式匹配两个文件名模式之一

python - 正则表达式替换所有除非行尾($ in [] issue)

python - 通过 Regex 操纵 Pandas 中的值

c# - PrecompileBeforePublish 使用 Msbuild

c# - C# 中的 PLSQL 过程参数

java - 使用括号拆分

javascript - 寻找正则表达式来满足以下条件