pavan pavan - 1 month ago 15
C# Question

Dynamic Regex replaces single backslash with double backslash in C#

In my code I am saving the Regular Expression for validating the UK Mobile number i.e. "^(+44\s?7\d{3}|(?07\d{3})?)\s?\d{3}\s?\d{3}$" in to the Sql server database.

On retrieving the expression to validate the mobile number the "\" will be replaced with the "\", this gives a serious issue as on checking it says the mobile number is invalid even though its valid. I tried to replace the double slash with single or even by replacing the slash with some special characters in the database.

If I give the regex expression statically it works fine for me:

C# Code:

bool isPhoneNumber = Regex.IsMatch(sColumnValue, @"^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$");
if (isPhoneNumber == true)
{
//Do something...
}
else
{
//Do something...
}


But replaces when I get the Regex string stored in database.I have replaced "\" with special characters in database "@#@" i.e.

"^(@#@+44@#@s?7@#@d{3}|@#@(?07@#@d{3}@#@)?)@#@s?@#@d{3}@#@s?@#@d{3}$"


C# code:

string sRegxE = Context.Fields.Where(s => s.Name == sColumnName).Select(s => s.ExpressionValue).FirstOrDefault();
string sExpression= sRegxE.Replace(@"@#@", @"\");
if (isPhoneNumber == true)
{
//Do something...
}
else
{
//Do something...
}


This doesn't work for me and I am getting the double slash instead of single slash with produces serious effect on Regex validation.

Can anybody help me to prevent the replacing of single backslash in C#, Cheers!!

Answer

Finally I solved it.

What I am doing here is creating a Regex object and passing the dynamic value from the Sql server database i.e. ^(+44\s?7\d{3}|(?07\d{3})?)\s?\d{3}\s?\d{3}$, then check whether the input matches.

Code:

      string sRegxE =dbContext.GetFields.Where(s => s.Name == sColumnName).Select(s => s.ExpressionValue).FirstOrDefault();
      Regex RgxM = new Regex("" + sRegxE + "");
      Match isPhoneNumber = RgxM.Match(sColumnValue);
       if (isPhoneNumber.Success)
         {
           //Do somthing...
         }

Reference: Capture variable string in a regular expression?