Donate

Regular Expression Word Boundary Not Working If Using A Variable In C#

In this scenario, I have to match an exact state abbreviation (QLD) that is Queensland. I declared an array containing state constant values. Normally this would work without using a string variable in C#:
Regex.IsMatch(address, @"\bQLD\b")
However, this won't work:
if (Regex.IsMatch(address, @"\b" + str + "\b"))
The solution is to put an @ sign on both "\b" of the expression:
string[] states = new string[]{"ACT","NSW","QLD"};  
  foreach (string str in states)  
  {  
    if (Regex.IsMatch(address, @"\b" + str + @"\b"))  
    {  
       state= str;  
       address = address.Replace(str, "").Trim();  
       break;  
    }  
  } 

Comments

Post a Comment

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Pass GUID As Parameter To Action Using ASP.NET MVC ContribGrid