我在C#中遇到.NET正则表达式问题。我们正在尝试匹配段落符号§
所包围的文本中的特殊标记。为了完整起见,相应的正则表达式被单词边界\b
包围。问题是由\b
包围的正则表达式与单词:
static void Main(string[] args)
{
string data = "I would like to replace this §pattern§ with something interesting";
string requiredResult = "I would like to replace this serious text with something interesting";
Regex regSuccess = new Regex("§pattern§");
Regex regFail = new Regex(@"\b§pattern§\b");
var dataSuccess = regSuccess.Replace(data, "serious text");
var dataFail = regFail.Replace(data, "serious text");
Console.WriteLine("regSuccess match: {0}", dataSuccess == requiredResult);
Console.WriteLine("regFail match: {0}", dataFail == requiredResult);
Console.WriteLine("Press enter to continue");
var line = Console.ReadLine();
}
如您所见,dataFail == requiredResult
会返回false
。
答案 0 :(得分:4)
替换
Regex regFail = new Regex(@"\b§pattern§\b");
与
Regex regFail = new Regex(@"§\bpattern\b§");
§
是一个非单词字符,因此\b
会阻止pattern
匹配。也许,你甚至不需要\b
,因为pattern
已经在非单词字符里面了?
Regex regFail = new Regex(@"§pattern§");