使用变量的C#正则表达式匹配

使用变量的C#正则表达式匹配,c#,regex,C#,Regex,我最熟悉PowerShell,最近开始使用C#作为我的主要语言。在PowerShell中,可以执行以下操作 $var1 = "abc" "abc" -match "$var1" 这导致了一个真实的陈述 我想用C语言做同样的事情。我知道你可以在C#中使用插值,我也尝试过各种方法来尝试使用Regex.Match(),但运气不好 例如: string toMatch = "abc"; var result = Regex.Match("abc", $"{{toMatch}}"); var a =

我最熟悉PowerShell,最近开始使用C#作为我的主要语言。在PowerShell中,可以执行以下操作

$var1 = "abc"
"abc" -match "$var1"
这导致了一个真实的陈述

我想用C语言做同样的事情。我知道你可以在C#中使用插值,我也尝试过各种方法来尝试使用Regex.Match(),但运气不好

例如:

string toMatch = "abc";

var result = Regex.Match("abc", $"{{toMatch}}");
var a = Regex.Match("abc", $"{{{toMatch}}}");
var b = Regex.Match("abc", $"{toMatch}");
var c = Regex.Match(toMatch,toMatch);
以上这些似乎都不起作用。我甚至不确定我想做的事在C#中是否可行。理想情况下,我希望能够使用变量和正则表达式的组合进行匹配。类似这样的
Regex.Match(varToMatch,$“{{myVar}}\\d+\\w{4}”)

编辑: 在阅读了这里的一些答案并尝试了一些代码之后,我真正的问题似乎是试图匹配目录路径。类似于“C:\temp\abcfile”的内容。例如:

string path = @"C:\temp\abc";
            string path2 = @"C:\temp\abc";
            string fn = path.Split('\\').LastOrDefault();

            path = Regex.Escape(path);
            path2 = Regex.Escape(path2);

            Regex rx = new Regex(path);

            var a = Regex.Match(path.Split('\\').Last().ToString(), $"{fn}");
//Example A works if I split and match on just the file name.

            var b = Regex.Match(path, $"{rx}");
//Example B does not work, even though it's a regex object.
            var c = Regex.Match(path, $"{{path}}");
//Example C I've tried one, two, and three sets of parenthesis with no luck
            var d = Regex.Match(path,path);
// Even a direct variable to variable match returns 0 results.

在上一个示例中,您似乎是对的,所以问题可能是您期望的是bool结果,而不是
匹配
结果

希望这个小例子有助于:

int a = 123;
string b = "abc";
string toMatch = "123 and abc";

var result = Regex.Match(toMatch, $"{a}.*{b}");

if (result.Success)
{
    Console.WriteLine("Found a match!");
}

您的代码运行良好(但只有在不添加额外大括号的情况下)。问题出在哪里?您需要
Regex.Escape
。使用
$@
而不是双重转义反斜杠。您只需执行以下操作:
var c=Regex.Match(“abc”,toMatch)
,然后检查
c.Success
请发布您遇到的实际问题的详细信息。您的示例非常有效。可能我遇到的问题是转义字符,因为我的最终目标是匹配两个目录路径。即使使用Regex.Escape()似乎也不太管用。啊,好吧。您应该更新您的问题以反映这一点!