Regex pass dynamic values with boundry

443 views Asked by At

I'm trying to pass a dynamic value at runtime with a boundary \b to a Regex function. My code is:

 static void Main(string[] args)
        {
            string sent = "Accelerometer, gyro, proximity, compass, barometer, gesture, heart rate";

            string match = "gyro";
            string bound = @"\b";

            if (Regex.IsMatch(sent, @"\bgyro", RegexOptions.IgnoreCase))
            {
                Console.WriteLine("match is in the sentence");
            }
            else if (Regex.IsMatch(sent, bound+match, RegexOptions.IgnoreCase))
            {
                Console.WriteLine("match is in the sentence");
            }

            Console.WriteLine(bound+match); outputs \bgyro
            Console.ReadLine();
        } 

First the if condition will be true since I'm passing the pattern to be matched directly. But when I'm trying to pass the pattern to be matched as in second condition it will be false. I tried to write the bound variable in console but it does not print any value in console either. Can some one give me a solution for this?

1

There are 1 answers

2
juharr On BEST ANSWER

Your first regular expression has a black slash followed by the letter b because of that @. The second one has the character that represents backspace. Just put an @ in front

string bound = @"\b";