C#Regex匹配问题

本文关键字:问题 C#Regex | 更新日期: 2023-09-27 18:27:34

当我试图将模式与字符串匹配时,我的代码中出现了这个问题,它将成功返回为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;
}            

C#Regex匹配问题

您可以使用TrimStart来确保开头有正确数量的反斜杠:

 String s = @"''''''''testestestest";
 s = @"''" + s.TrimStart('''');

总是在开头有2。如果我误解了你的目标,请告诉我。

从OP,user2619395:

万一将来有人对此有问题,我就想出来了。原因是它不匹配的原因是它查看的是文本格式的路径,而不是C#在调试器中看到的格式。因此,这条路只有一条,同时它正在寻找两条,所以永远不会奏效。如果这有意义的话。

(用户2619395,请随意添加您自己的答案。完成后请在这篇文章上留言,我将删除这篇文章。)