【发布时间】:2021-09-03 10:25:41
【问题描述】:
我已经尝试了几个版本的多少个“\”来匹配 ()。模式需要一加一才能在字符串中得到它。
--fixme.h--
#
_TARGET_VERSION = $(_TARGET_VERSION_GREEN)
#
--Program.cs--
static void Main(string[] args)
{
var expr = "(_TARGET_VERSION = \\$\\(_TARGET_VERSION_GREEN\\))";
var repl = "!if 0\n$1\n!endif";
var content = File.ReadAllText("fixme.h");
var searchOptions = RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline;
var matched = Regex.Match(content, expr, searchOptions);
if (matched.Success)
{
var newContent = Regex.Replace(content, expr, repl, searchOptions);
File.WriteAllText("fixed.h", newContent);
}
}
【问题讨论】:
-
这不是笔误,也不是非repro,问题是代码的匹配部分不能改,选项不能去掉。必须了解正则表达式选项的工作原理以及它们如何影响模式,这样才能解决问题。