简体   繁体   中英

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. :)

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];

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

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

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