【发布时间】:2013-08-13 14:23:53
【问题描述】:
当我尝试将模式与将成功返回为假的字符串匹配时,我在代码中遇到了这个问题... 我用来测试表达式的站点是http://regexhero.net/tester/
在我们进入代码之前有一点背景:
我正在使它尽可能通用。有一些路径可能会在此过程中产生额外的\,所以为了清理它,如果在清理它的路径中有两个以上的\,我首先使用正则表达式。问题是一些路径,因为它们来自服务器,所以路径名中有四个\(只有两个\,但由于它的C#编译器希望它是四个\ 's) 因此,第二步是在路径的开头添加额外的两个\,以满足一切并让事情变得更好。
这是我将使用的路径示例,因此您有一个想法:
\\\\moon\Release_to_Eng\V11\Client
这是我的代码:
//pass over the value of what the user selected into the global variable
GlobalVars.strPrevVersion = GlobalVars.strDstPath + "\\" + cboVerPath.Text;
//if there are more than two \'s in the path then replace them
GlobalVars.strPrevVersion = Regex.Replace(GlobalVars.strPrevVersion, @"\\{2,}", "\\");
//check to see if there are two \'s at the begining of the path name
Match match = Regex.Match(GlobalVars.strPrevVersion, @"^\\\\");
//if there are two \'s in the begining of the path name then add two more.
if (match.Success) << THIS is where it goes wrong the Success returns false even though it should match
{
GlobalVars.strPrevVersion = @"\\" + GlobalVars.strPrevVersion;
}
【问题讨论】:
-
你确定你的字符串中有 \\\\ 吗?听起来你有 \\ ,它被转义到 \\\\ 。
-
您已经使用@ 来逃避反弹。您不需要添加额外的反斜杠。例如。 Regex.Match(GlobalVars.strPrevVersion, @"^\\\\");实际上是检查 4 个反斜杠,而不是 2 个。
-
@Reubz 是的。您需要在 RegEx 字符串中转义反斜杠
-
一个简单的测试确认
Regex.Match(@"\\helo","^\\\\")成功匹配。您确定您没有查看调试器中的输入,并且将单个反斜杠误解为两个吗?调试器在字符串上显示转义序列,因此字符串@"\helo"在调试器中将显示为\\helo。 -
没关系,我想通了。