正则表达式匹配找不到匹配项

时间:2019-10-01 11:55:00

标签: c# regex match

我正在使用Visual C#创建一个小的工具来支持某些人进行简单的文本操作。该工具具有GUI,但在代码中使用了正则表达式。大多数事情已经可以工作了,但是现在我发现了一个我无法解决的问题。我想在单词的开头找到字符串MY2020。这是我的代码:

string TestString = "we have the string MY2020 somewhere in the line";
string Pattern = "\bMy2020";
RegexOptions options = RegexOptions.IgnoreCase;
MatchCollection myMatches = Regex.Matches(TestString, Pattern, options);
if (myMatches.Count > 0)
{

我希望能找到MY2020。因此,myMatches.Count应该为1,但应为0。 同时,我使用在线正则表达式测试器(https://regex101.com/)。这是一场比赛。 我想念什么?

1 个答案:

答案 0 :(得分:-1)

您需要转义“ \”,我已将您的代码修改为

      string TestString = "we have the string MY2020 somewhere in the line";
      string Pattern = @"\bMy2020";
      RegexOptions options = RegexOptions.IgnoreCase;
      MatchCollection myMatches = Regex.Matches(TestString, Pattern, options);
      if (myMatches.Count > 0)
相关问题