【问题标题】:Regex.Matches doesn't find match [duplicate]Regex.Matches 找不到匹配项 [重复]
【发布时间】:2020-01-30 17:11:06
【问题描述】:

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

【问题讨论】:

  • 你不会使用 \\bMy2020 吗?你确定里面有退格键吗?
  • "\b" 代表退格字符。您需要转义反斜杠

标签: c# regex match


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2017-10-11
    相关资源
    最近更新 更多