10

I want to extract date from the string through regex.

String : log-bb-2014-02-12-12-06-13-diag

How to do it?

9
  • 2
    How about just split your string with - and concatenate items which they contains only numbers? Commented Feb 12, 2014 at 9:29
  • hav to do only through regex.... Commented Feb 12, 2014 at 9:31
  • How does you regex look so far? Commented Feb 12, 2014 at 9:31
  • 3
    regexone.com is a good start Commented Feb 12, 2014 at 9:35
  • 2
    @ManishTiwari what should be the date in the string you have mentioned ? is it 12th feb 2014 or 12th june 2013 ? Commented Feb 12, 2014 at 9:39

4 Answers 4

13

Here something to start:

string s = "log-bb-2014-02-12-12-06-13-diag";
Regex r = new Regex(@"\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}");
Match m = r.Match(s);
if(m.Success)
{
    DateTime dt = DateTime.ParseExact(m.Value, "yyyy-MM-dd-hh-mm-ss", CultureInfo.InvariantCulture);
}
Sign up to request clarification or add additional context in comments.

3 Comments

@"\d{4}(-\d\d){5}"
System.Globalization.CultureInfo.InvariantCulture
The using statement is using System.Text.RegularExpressions;
11

Try this

(\d+)[-.\/](\d+)[-.\/](\d+)

Regex Demo.

It will match all date formats

Comments

3

Considering your date to be just 2014-02-12 i.e. 12th feb 2014.I hev written the below code to extract that part using ruby

str = 'log-bb-2014-02-12-12-06-13-diag'

str.scan(/\d{4}.\d{2}.\d{2}/)

will return ["2014-02-12"]

regex is written within two /

\d means any integer, {} curly braces with any integer means number of times it has been repeated, . means any character. Here I have used it for -

Comments

0

I have checked all above suggestions but none worked for if date format is "November 11, 2000". As this was a constant format that I need to extract for my problem here is the solution for it.

[A-Z]\w*\s\d*\W*\d{4}

Note: This regex is specifically to extract date in the above mentioned format, if the order is randomized for eg. "11 November, 2000". This Regex won't give suitable result. However slight modification in the above re, would give proper results.

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.