user1386966
user1386966

Reputation: 3402

c# How to look for specific pattern in a string?

I have a string containing letters and numbers. This string also contains a Date that I want to extract.

example : anv749dld95hd01/01/2012ncjf739dkcju

I want to get new string that will contain : 01/01/2012

The only thing I thought is to split it using :str.Split('/') this way I will get an array and work on each cell - take the two last characters of the first cell, get the value of the second cel and then get the first 4 characters from the third cell.

Is there a better way to do it?

Upvotes: 0

Views: 198

Answers (3)

Adil
Adil

Reputation: 148180

You can use Substring, you can find the first forward slash and start substring two characters before and take ten characters.

string date = str.Substring(s.IndexOf('/')-2, 10);

You can Parse the substring using DateTime.TryParseExact you have to ensure if you got the right substring.

bool isParsed = DateTime.TryParseExact(date, "dd/MM/YYYY", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out x1);

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503869

Well you could potentially use a regular expression:

using System;
using System.Text.RegularExpressions;

class Test
{    
    static void Main()
    {
        var input = "anv749dld95hd01/01/2012ncjf739dkcju";
        var regex = new Regex(@"\d{2}/\d{2}/\d{4}");
        var match = regex.Match(input);
        if (match.Success)
        {
            Console.WriteLine("Got match: {0}", match.Value);
        }
        else
        {
            Console.WriteLine("No match found");
        }
    }
}

(You could call Match.NextMatch to check that there's only one match.)

To parse this as a DateTime, you'd then use something like this:

string dateText = match.Value;
DateTime date;
if (DateTime.TryParseExact(dateText, "dd/MM/yyyy",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None, out date))
{
    // Use date
}
else
{
    // Couldn't parse the value
}

(We can't tell whether it's meant to be dd/MM/yyyy or MM/dd/yyyy; adjust as required.)

You could also additionally tighten up the regex if you wanted, such that the first digit of the month has to be 0 or 1, and the first digit of the day has to be 0, 1 or 2. It depends on what your data is like, really.

Upvotes: 5

Michal Ciechan
Michal Ciechan

Reputation: 13898

Use RegEx to find the pattern and return the desired string.

Upvotes: 0

Related Questions