How it works...

Let's have a closer look at the regex generated. The line of code we are looking at is the return statement in the extension method:

return Regex.IsMatch(value,  $@"^acm[_]{DateTime.Now.Year}[_]({DateTime.Now.Month}|0[{DateTime.  Now.Month}])[_]({DateTime.Now.Day}|0[{DateTime.Now.Day}])(.txt|.docx|.xlsx)$");

To appreciate what is happening, we need to break this expression up into the different components:

The conditional OR Description
| This denotes the OR metacharacter.
The file prefix and separator Description
acm The file must begin with the text acm.
[_] The only valid separator between the date components and the prefix in the file name is an underscore.
The date parts Description
{DateTime.Now.Year} The interpolated year part of the date for the file name.
{DateTime.Now.Month} The interpolated month part of the date for the file name.
0[{DateTime.Now.Month}] The interpolated month part of the date with a leading zero for the file name.
{DateTime.Now.Day} The interpolated day part of the date for the file name.
0[{DateTime.Now.Day}] The interpolated day part of the date with a leading zero for the file name.
Valid file formats Description
(.txt|.docx|.xlsx) Match any of these file extensions for text documents, Word documents, or Excel documents.
Start and end of string Description
^ Tells the regex engine to start at the beginning of the given string to match
$ Tells the regex engine to stop at the end of the given string to match

Creating the regex in this manner allows us to always have it stay up to date. As we have to always match the current date to the file being validated, this creates a unique challenge that is easily overcome using string interpolation, DateTime, and regex OR statements.

Having a look at some of the more useful bits of regex, you will see that this chapter has not even begun to scratch the surface of what can be accomplished. There is a whole lot more to explore and learn. There are many resources on the Internet as well as some free (some online) and commercial tools that will assist you in creating regex.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.11.247