c# - 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/)。这显示了一场比赛。我错过了什么?
解决方案
您需要转义“\”,我已将您的代码修改为
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)
推荐阅读
- javascript - 如何正确地为 iOS 构建 react-native 应用程序?
- javascript - peer.js 聊天应用程序中未收到消息
- ruby - 字母、空格和连字符的正则表达式
- python - 在 python 中计算 mph 的最佳方法
- python - 将值从一个 python 脚本发送到另一个已经运行的脚本
- csv - 在 D3 中加载 CSV 会更改字符值
- php - jquery - ajax - 逐个更新列的问题
- reactjs - 递归渲染反应组件?
- php - 获取数据后保持选择的值并查询以将其插入数据库
- android - 如何使用 com.sun.webkit 编译 Android 项目