使用c#从长字符串中可靠地提取特定日期模式

时间:2014-01-23 05:05:08

标签: c# asp.net

每次如何可靠地提取“20130901” - 请参阅下面的代码?如果有匹配,我可以解析为日期。它的格式始终为yyyyMMdd

            string s = "X23_CBW_13CP05AUGR1_20130901000000";
            Regex rg = new Regex("\\d+");
            Match m = rg.Match(s);

非常感谢

3 个答案:

答案 0 :(得分:0)

将正则表达式更改为仅提取8位数字序列,然后ParseExact第一场匹配:

string s = "X23_CBW_13CP05AUGR1_20130901000000";
Regex rg = new Regex(@"\d{8}");
Match m = rg.Match(s);


if (m.Success)
{
    DateTime d = DateTime.ParseExact(m.Value, "yyyyMMdd",
                      CultureInfo.InvariantCulture);
    // ... 
    // Do something with your value here
}

高级实施又称Overkill

如果您需要引擎找到第一个有效日期字符串,即使之前有其他长数字序列,您也可以实现:

string s = "X23CBW13992238455222348CP05AUGR120130901000000";
Regex rg = new Regex(@"\d{8,}");
MatchCollection mc = rg.Matches(s);

DateTime? d = null;


foreach (Match m in mc)
{
    string digits = m.Value;

    for (int n = 0; n < digits.Length - 8; n++)
    {
        try
        {
            d = DateTime.ParseExact(digits.Substring(n, 8), "yyyyMMdd",
                CultureInfo.InvariantCulture);
            break;
        }
        catch
        { }
    }

    if (d != null)
        break;
}


if (d != null)
{
// Use your value here
}

答案 1 :(得分:0)

您可以为此

使用子字符串
     string ans;

     string input="X23_CBW_13CP05AUGR1_20130901000000";

        int index = input.LastIndexOf("_");
        ans = input.Substring(index+1,8);

        Console.WriteLine("Substring: {0}", ans);

希望这能帮到你!

答案 2 :(得分:0)

尝试这种模式,

/\d{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|[3][0-1])/g