Nitin Kumar Nitin Kumar - 25 days ago 9
ASP.NET (C#) Question

How to Write Custom Regex To Match A String

I am working on a Dynamic SMS Templates below is my code

My Original SMS Template like this

string str="Dear 123123, pls verify your profile on www.abcd.com with below login details: User ID : 123123 Password: 123123 Team- abcd";


Here 123123 could be replaced with any thing like below ex-

Dear Ankit, pls verify your profile on www.abcd.com with below login details: User ID : Ankit@123 Password: Ankit@123 Team- abcd


Now How can i make sure that string matched everything same except 123123 which can be any thing dynamic value like
Ankit,Ankit@123


string ss="Dear Ankit, pls verify your profile on www.abcd.com with below login details: User ID : 123 Password: 123 Team- abcd";
Regex Re = new Regex("What Regex Here");
if(Re.IsMatch(ss))
{
lblmsg.Text = "Matched!!!";
}
else
{
lblmsg.Text = "Not Matched!!!";
}

Answer
@"^Dear (\S+?), pls verify your profile on www\.abcd\.com with below login details: User ID : (\S+) Password: (\S+) Team- abcd$"

// A ^ to match the start, $ to match the end, \. to make the dots literal
// (\S+) to match "one or more not-whitespace characters" in each of the 123123 places.
// @"" to avoid usual C# string escape rules
// Not sure what happens to your template if the name or password has spaces in.

e.g.

using System;
using System.Text.RegularExpressions;

class MainClass {
  public static void Main (string[] args) {
    string ss="Dear Ankit, pls verify your profile on www.abcd.com with below login details: User ID : 123 Password: 123 Team- abcd";

        Regex Re = new Regex(@"^Dear (\S+), pls verify your profile on www\.abcd\.com with below login details: User ID : (\S+) Password: (\S+) Team- abcd$");

        if(Re.IsMatch(ss))
        {
           Console.WriteLine ("Matched!!!");
        }
        else
        {
            Console.WriteLine ("Not Matched!!!");
        }
  }
}

Try it online at repl.it

Comments