Monday, September 17, 2012

Regex Word Boundary (Not working if using a variable)

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#:
Code:
Regex.IsMatch(address, @"\bQLD\b")
However, this won't work:
Code:
if (Regex.IsMatch(address, @"\b" + str + "\b"))
The solution is to put an @ sign on both "\b" of the expression:
Code:
  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;  
    }  
  } 

1 comments: