Regular Expressions - Match First or Last Characters

Regular Expressions - Match First or Last Characters

Match a string that starts with or ends with a specified search term

I haven't posted anything in a month now. Without going into too much detail, the 3rd wave of COVID-19 hit home this time. My family is fine for now but it was a massive upheaval in our lives. But there is no time to cry. I move forward, the only direction.

The way forward

To my one follower reading this (or future followers that might come back to this), I'm still going to continue writing about Price Book Club. Price Book Club will be a retail price tracking web application where users can save their prices and compare prices with their past purchases and purchases of other users.

I'm currently reading a book by Les Jackson on .NET Core API development. It's a great read. I'm about halfway through the book. Once I'm done, I can start writing more about the Price Book Club project. Until then, I'll be writing short articles about coding problems I come across. This might help cement the concepts I don't grasp yet. This brings me to Regular Expressions.

Regular Expressions

Regular expressions are pretty cool. It helps you filter strings for whatever search term you are looking for. I tried using it before but failed miserably. What I was trying to achieve was to extract the vendor name and total payment amount from an email whenever I made a payment with one of my cards.

But now, I need to use it for a reporting tool I developed for my employer. The tool only sends out reports in PDF but there was a request to send the report in CSV as well. This is where regular expressions come in. The solution I'm implementing is not very elegant but the users need it urgently. If it works, why stress about elegance? Future me is probably crying under a desk right now trying to maintain this code.

Match First Characters

After saving the PDF, the application needs to update the database with the location of the file. This location is used later when the application needs to send the report. The file extension is hard-coded to save as ".pdf".

My solution is to look for the term "CSV" at the start of the file name and if it contains those 3 letters, it will save the file as ".csv" instead. Yeah, I know, not elegant at all. I'm going to test it in a console app first before I write the code in the reporting application.

First I need to add the using statement so that I can use regular expressions.

using System;
using System.Text.RegularExpressions;

namespace RegularExpression
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

I'll remove the Console.WriteLine("Hello World!") and add my code in there. Add an array with two report names, one with Csv at the beginning and another without.

string[] ReportNames = { "TPSReport", "CsvReport" };

yeah-about-those-hf8r1b.jpg

This is where Regex comes into play. I have to create a regular expressions pattern. I need to use special characters and then the term I'm searching for. ^ matches at the start of the string and $ matches at the end of the string. So for my use case, I'll use ^.

var csvMap = new Regex(@"^Csv");

Then I just need to use IsMatch and then it should return a bool with either true or false.

if (csvMap.IsMatch(report))

That's it. Here is the full code. It seems to work like I wanted to. This is the easy stuff. I'll get into the more difficult patterns later.

using System;
using System.Text.RegularExpressions;

namespace RegularExpression
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] ReportNames = { "TPSReport", "CsvReport" };

            var csvMap = new Regex(@"^Csv");

            foreach(string report in ReportNames)
            {
                if (csvMap.IsMatch(report))
                {
                    Console.WriteLine($"The report {report} is a CSV file");
                }
                else
                {
                    Console.WriteLine($"The report {report} is a PDF file");
                }
            }

            Console.ReadKey();
        }
    }
}
 
Share this