Tuesday, December 16, 2014

Learning Regex (file name with .txt extension)

I've gone through 6-7 web pages and 2 tutorials.  I did an initial search for a regex for a file name.  I didn't search but a minute or two then decided I need to learn a little more about regular expressions than just how to come up with one to recognize a file name.

After reading through a lot of documentation, I believe I came up with what I needed but first a little background.

I'm on lesson 36 of Learn Ruby the Hard Way.  I'm not making a game like the home suggests to.  Instead, I'm making a script that will ask for eight pieces of information and it will create a tab delimited file with each piece of information.  I'm giving the user the option to name the file.  The requirements will be that it must only contain letters (upper/lower case), digits, a hyphen and an underscore character and the file extension must end with a ".txt" (without the double quotes).  If the user types in anything else, it won't be accepted.

So I'm still at the beginning of creating this script and had to stop for a few days to learn how to put together regular expressions.  This is what I have so far for an acceptable file name.

I chose this type of project over creating a game because I need to ultimately create a script that parses a tab delimited file and combines rows/records based on values in 2 columns.  That will be my next project.

Here's the regex that I came up with to accept a file name with the above mentioned requirements.

/^[^\W+]\w+\-?(.txt$)/

I'm always open for suggestions on simplifying my code. I'm in no way an expert but the above expression works for what I need it for.  I'll be studying regular expressions in more depth as I continue on with my projects.

No comments:

Post a Comment