Regular Expression to replace a pattern at runtime(C#3.0)
I have a requirement.
I have some files in a folder among which some file names looks like say
**EUDataFiles20100503.txt, MigrateFiles20101006.txt.**
Basically these are the files that I need to work upon.
Now I have a config开发者_如何学Go file where it is mentioned as the file pattern type as
EUDataFilesYYYYMMDD, MigrateFilesYYYYMMDD.
Basically the idea is that, the user can configure the file pattern and based on the pattern mentioned, I need to search for those files that are present in the folder.
i.e. at runtime the YYYYMMDD will get replaced by the Year Month and Date Values. It does not matter what dates will be there(but not with time stamp ; only dates)).
And the EUDataFiles or MigrateFiles names will be there.(they are fixed)
i.e. If the folder has a file name as EUDataFile20100504.txt(i.e. Year 2010, Month 05, Day 04) , I should ignore this file as it is not EUDataFiles20100504.txt (kindly note that the name is plural - File(s) and not file for which the system will ignore the file).
Similarly, if the Pattern given as EUDataFilesYYYYMMDD and if the file present is of type EUDataFilesYYYYDDMM then also the system should ignore.
How can I solve this problem? Is it doable using regular expression(Replacing the pattern at runtime)?
If so can anyone be good enough in helping me out?
I am using C#3.0 and dotnet framework 3.5.
Thanks
You could construct a regex from your basic file name plus (depending on the pattern) sub-regexes.
The sub-regexes could be
yyyy = @"\d{4}"
(unless you want to restrict a certain year range)
mm = @"(1[0-2]|0[1-9])"
dd = @"(3[01]|[12][0-9]|0[1-9])"
Build your regex by adding them in the correct order:
re = @"\AEUDataFiles" + yyyy + mm + dd + @"\.txt\Z"
Then you can check whether the filename(s) you've found match the regex:
foundMatch = Regex.IsMatch(subjectString, re);
Of course, this isn't a validation for correct dates (20100231 would pass), but that's probably not a problem in this case.
精彩评论