Friday, August 11, 2017

Is there a better way?

Maybe it is not the trendiest tool, but I just endorse Visual Studio for figuring out RegEx patterns. I will make a ceremonial silly solution and then bolt a unit test project onto it and write some unit tests around a regular expression pattern. What follows proves out a pattern that validates an eight digit string with no spaces wherein a dot divides the first six and the last two digits and the first six digits may also be alphanumeric. A coworker asked me for this today. I know there are other tools for this. This is what I do though.

using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject
{
   [TestClass]
   public class RegExTests
   {
      private const string myPattern = @"^[0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z]
            [0-9A-Za-z][0-9A-Za-z]\.[0-9][0-9]$";
      
      [TestMethod]
      public void Test1()
      {
         string toMatch = "123456.89";
         bool isMatch = (Regex.IsMatch(toMatch, myPattern));
         Assert.AreEqual(isMatch, true);
      }
      
      [TestMethod]
      public void Test2()
      {
         string toMatch = "abcdef.89";
         bool isMatch = (Regex.IsMatch(toMatch, myPattern));
         Assert.AreEqual(isMatch, true);
      }
      
      [TestMethod]
      public void Test3()
      {
         string toMatch = "123456.8x";
         bool isMatch = (Regex.IsMatch(toMatch, myPattern));
         Assert.AreEqual(isMatch, false);
      }
      
      [TestMethod]
      public void Test4()
      {
         string toMatch = "123456.8";
         bool isMatch = (Regex.IsMatch(toMatch, myPattern));
         Assert.AreEqual(isMatch, false);
      }
      
      [TestMethod]
      public void Test5()
      {
         string toMatch = "12345.89";
         bool isMatch = (Regex.IsMatch(toMatch, myPattern));
         Assert.AreEqual(isMatch, false);
      }
      
      [TestMethod]
      public void Test6()
      {
         string toMatch = "1234 6.89";
         bool isMatch = (Regex.IsMatch(toMatch, myPattern));
         Assert.AreEqual(isMatch, false);
      }
   }
}

No comments:

Post a Comment