C#Regex - 如何忽略带变量的转义序列

时间:2022-09-13 00:15:06

Say I have this code:

说我有这个代码:

foreach (string filepath in someList)
{
    someBool = Regex.IsMatch(someString, filepath);
}

Where someBool, someList, and someString are just a random boolean, list, and string, respectively (This is a simple example of what I'm trying to do). Filepath is a filepath, with a bunch of backslashes (i.e. C:\\somefolder\somefile). The problem is by running this code, I get an ArgumentException error, with an "unrecognized escape sequence" problem for things like "D:\\H..." I tried using

someBool,someList和someString分别只是一个随机的布尔,列表和字符串(这是我正在尝试做的一个简单的例子)。 Filepath是一个文件路径,带有一堆反斜杠(即C:\\ somefolder \ somefile)。问题是运行此代码,我得到一个ArgumentException错误,“D:\\ H ...”之类的“无法识别的转义序列”问题我尝试使用

someBool = Regex.IsMatch(someString, @filepath);

and I am still seeing the error. Is there something else I'm forgetting?

我仍然看到错误。还有别的我忘了吗?

1 个解决方案

#1


6  

Have you tried using Regex.Escape

您是否尝试过使用Regex.Escape

Regex.IsMatch(someString, Regex.Escape(filepath));

#1


6  

Have you tried using Regex.Escape

您是否尝试过使用Regex.Escape

Regex.IsMatch(someString, Regex.Escape(filepath));