muhihsan
muhihsan

Reputation: 2350

Get substring from string date using regex

I have this string "Date.2014.07.04"

Then if I want to get "07" from string above using regex.

How do I do that?

I don't want to use split.

Why I don't want to use split? Because when we split, the result will be in array of string. And usually we'll try to get the index of array that we want. In my case it will be

var date = "Date.2014.07.04";
date.Split('.')[2];

But let say we update the date to new string (Remove all '.').

var date = "Date20140704";
date.Split('.')[2];

This will throw an error because it can't find index number 2.

By using regex, this error won't occur and it will just return empty string if the pattern that we want can't be found inside string. :)

Upvotes: 0

Views: 841

Answers (3)

NeverHopeless
NeverHopeless

Reputation: 11233

It is a good advvice to use a datetime function like ParseExact or TryParse or TryParseExact etc since it will validate each part as well. But if you really need regex, have a look at this one, it will validate month part as well:

(0?[1-9]|1[0-2])\.\d{2}$

Demo

Upvotes: 0

Adil
Adil

Reputation: 148140

You better parse the date and then get the desired part using DateTime.ParseExact but you have to remove Date. from the date string first.

DateTime dt = DateTime.ParseExact(strDate.Replace("Date.",""), "yyyy.MM.dd", CultureInfo.InvariantCulture);
int month = dt.Month;

You can also use string.Split

string month =  strDate.Split('.')[2];

Upvotes: 6

Amit Joki
Amit Joki

Reputation: 59252

Just do this:

"Date.2014.07.04".Split('.')[2];

Since you are insisting on Regex, do this:

var value = Regex.Match("Date.2014.07.04",@"(?<=\w{4}\.\d{4}\.)\d+").Value

Upvotes: 1

Related Questions