简体   繁体   中英

With c# extract a specific date pattern reliably from a long string

How does one reliably extract "20130901" each time - see code below? If there is a match I can then parse to a date. Its always in the format yyyyMMdd

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

Many thanks

Change your regular expression to only pull out 8 digit numeric sequences and then ParseExact the first match:

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
}

Advanced Implementation aka Overkill

If you need the engine to find the first valid date string, even if there are other long number sequences before it, you could implement:

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
}

You can use substring for this

     string ans;

     string input="X23_CBW_13CP05AUGR1_20130901000000";

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

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

Hope this helps you!

试试这个模式

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM