Click here to Skip to main content
15,745,750 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +

I have a file that is named as uk_mcn_20190201_feed.xml. The thing is that it is in yyyyMMdd format and it can be written anywhere in the file name. I mean something like:




I want to extract the number from the file name, parse it as yyyyMMdd and write it as dd-mm-yyyy in my XML file.

I have got the file name but I don't know how to extract the numbers.

I think that if I use Regex, then it will help but in that case I think checking for a condition that the number is 8 digit long will help. So that, wherever in the file name, if it finds the eight digit numbers, it will extract it and store it in a string and parse it from there.

Please help.


What I have tried:

var mat = Regex.Match(stringValue, @"\d+").Value; //I have just done the extraction
Updated 5-Feb-19 14:45pm

Once you have the number you can use DateTime.TryParse Method (System) | Microsoft Docs[^]. A little more Googling on your part would pay dividends.
Share this answer
The regex for a eight digit sequence is simple:

To convert that to a DateTime is also simple:
DateTime dt;
if (!DateTime.TryParseExact(yourStringBasedDate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    // report problem or log it
You can then format the DateTime value as you wish (or better, leave that to the XML generator)
Share this answer
Another way is to remove non-digit characters. See:
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InvariantCulture;
string[] files = {"uk_mcn_20190201_feed.xml",
var filesAndDates =  files
	.Select(x=> new 
			FileName = x,
			Date = DateTime.ParseExact(Regex.Replace(x, @"\D", ""), "yyyyMMdd", ci) //here non-digits are replaced with empty string
foreach(var fad in filesAndDates)
	Console.WriteLine("{0}\t{1}", fad.FileName, fad.Date);
Share this answer
Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre -[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900