简体   繁体   中英

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!!!";
        }
@"^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.

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM