首页 > 解决方案 > Regex.Matches 找不到匹配项

问题描述

我正在使用 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/)。这显示了一场比赛。我错过了什么?

标签: c#regexmatch

解决方案


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

      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)

推荐阅读