我在我的代码中遇到了这个问题,当我试图匹配一个模式和一个字符串时,它将成功返回为false……我用来测试这个表达式的站点是http://regexhero.net/tester/
在我们开始编写代码之前,先介绍一下背景知识:我会让它尽可能的通用。有一些路径可能会产生额外的\,所以为了清理它,我首先使用一个正则表达式,如果路径中有两个以上的\,它就会清理它。这样做的问题是,一些路径,因为它们来自服务器,在路径名中有四个\(通常只有两个\,但是由于它的C#,编译器希望它是四个\)。因此,第二步将是在路径的开始添加额外的两个\,以满足所有条件并使事物更好地流动。
下面是一个我将使用的路径的示例,这样您就会有一个想法:
\\\\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;
} 发布于 2013-08-13 22:29:31
您可以使用TrimStart来确保开头的反斜杠数量正确:
String s = @"\\\\\\\\testestestest";
s = @"\\" + s.TrimStart('\\');将始终将2放在开头。如果我误解了你的目标,请告诉我。
发布于 2013-08-14 00:53:04
在行动中,user2619395
只是为了以防将来有任何人对此有问题,我想出来了。它不匹配的原因是它查看的是文本格式的路径,而不是C#在调试器中看到的格式。因此,路径只有一个,\同时它正在寻找两个,所以它永远不会工作。如果这有任何意义的话。
(user2619395,请随意添加您自己的答案。请在您完成后在此帖子上留言,我将删除此帖子。)
https://stackoverflow.com/questions/18211737
复制相似问题