2

I have strings that are similar to the ones below:

string str1 = "test_20150505";
string str2 = "test_20150505_yts";
string str3 = "test_all";
string str4 = "test";

The below regex code extracts date (20150505) for string str1 and for string str3 & string str4 returns empty, which is also fine.

However, what do I have to change so as to extract date for string str2?

string d = Regex.Match(str1, "^(?:.*_)?([0-9]{8})(?:\\..*)?$").Groups[1].Value.ToString();
2
  • 1
    Can you explain why do you need (?:\\..*)? part in your regex? Non of yours examples dates ends with .. Commented May 28, 2015 at 9:52
  • Are all the dates in the YYYYMMDD format? Commented May 28, 2015 at 14:55

2 Answers 2

2

You can just check for optional _s around 8-digits numbers:

(?<=_|\b)[0-9]{8}(?=_|\b)

See demo

var rx = new Regex(@"(?<=_|\b)[0-9]{8}(?=_|\b)");
var inputs = "test_20150505\n\test_20150505_yts\ntest_all\ntest";
var results = rx.Matches(inputs).OfType<Match>().Select(p => p.Value).ToList();

enter image description here

Then, you can parse the date, e.g.:

DateTime datetime;
DateTime.TryParseExact(results[0], "yyyyMMdd", new System.Globalization.CultureInfo("en-us"), System.Globalization.DateTimeStyles.None, out datetime);

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Your last part of the regex pattern seems to be a typo. Use

string d = Regex.Match(str1, "^(?:.*_)?([0-9]{8})(?:_.*)?$").Groups[1].Value.ToString();

instead.

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.