我正在尝试在我的正则表达式模式中使用变量。此变量将始终更改,并且永远不会相同。
每当我尝试在模式中使用它时,它都会给我一个错误。由于变量im using是一个路径,它会看到" \"作为一个转义序列和任何一个字母,例如" c:\ users"会被视为" \ u"这给了我一个错误。
我想知道是否有任何解决方法,就像我说这个变量总是在变化,硬编码任何值都不会起作用。
这是我现有的正则表达式代码:
public static Boolean validateFilePath(String dstPath, String newFileDstPath)
{
Boolean blnflag = false;
Match m = Regex.Match(newFileDstPath, @""+ dstPath + "");
if (m.Success)
{
blnflag = true;
}
return blnflag;
}
答案 0 :(得分:6)
使用Regex.Escape方法?见http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape(v=vs.110).aspx
答案 1 :(得分:1)
如果您READ THE DOCUMENTATION,您会发现方法Regex.Escape()
,这可能会达到您的目的。
其他一些说明:
你为什么要这样做:@"" + dstPath + ""
解析为dstPath
,不变。
为什么要尝试使用正则表达式来处理使用string.StartsWith()
和/或System.IO.Path