Regex通过带有边界的动态值

本文关键字:动态 边界 Regex | 更新日期: 2023-09-27 17:57:29

我试图在运行时将一个带有边界'b的动态值传递给Regex函数。我的代码是:

 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();
        } 

首先,if条件将为真,因为我正在传递要直接匹配的模式。但当我试图像在第二种情况下那样传递要匹配的模式时,这将是错误的。我试图在控制台中编写绑定变量,但它也没有在控制台中打印任何值。有人能给我一个解决方案吗?

Regex通过带有边界的动态值

由于@,第一个正则表达式后面有一个黑色斜线,后面跟着字母b。第二个具有表示退格的字符。只需在前面放一个@

string bound = @"'b";