0

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

8
  • 1
    Split and get the 3rd element? Commented Apr 7, 2014 at 4:51
  • I'm with @Jerry Regex isn't the easiest thing in the word to deal with and if it's always going to be this format, then you can do String.split('.')[2] (Sorry if syntax isn't perfect on that) Commented Apr 7, 2014 at 4:53
  • fwiw, the best way to do this is to use one of date.parse family of functions and then take the Month property. Commented Apr 7, 2014 at 4:53
  • Why do you not want to use split? Commented Apr 7, 2014 at 4:53
  • And may I know why you don't want it? Commented Apr 7, 2014 at 4:53

3 Answers 3

6

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];
Sign up to request clarification or add additional context in comments.

1 Comment

That's pretty neat that you can define a term ('Date') that the ParseExact method will expect, I didn't know that
1

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

4 Comments

Glad to have helped you ;)
I put the reason why I don't want to use split :)
@IhsanMuhammad, well, in that case my regex wont work
Yes, I will know that this doesn't work when it returns empty string. Instead of throwing an error while we use split. Btw thanks again.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.