我正在写一个翻译,而不是任何认真的项目,只是为了好玩,并且对正则表达式更加熟悉.从下面的代码中我想你可以找到我要去的地方(cheezburger有人吗?).
我正在使用一个字典,它使用正则表达式列表作为键,字典值是List<string>包含更多值的替换值的字典.如果我打算这样做,为了弄清楚替补是什么,我显然需要知道关键是什么,我怎样才能找出触发匹配的模式?
var dictionary = new Dictionary<string, List<string>>
{
{"(?!e)ight", new List<string>(){"ite"}},
{"(?!ues)tion", new List<string>(){"shun"}},
{"(?:god|allah|buddah?|diety)", new List<string>(){"ceiling cat"}},
..
}
var regex = "(" + String.Join(")|(", dictionary.Keys.ToArray()) + ")";
foreach (Match metamatch in Regex.Matches(input
, regex
, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
{
substitute = GetRandomReplacement(dictionary[ ????? ]);
input = input.Replace(metamatch.Value, substitute);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试什么,或者有更好的方法来实现这种疯狂吗?
您可以在正则表达式中为每个捕获组命名,然后在匹配中查询每个命名组的值.这应该可以让你做你想做的事.
例如,使用下面的正则表达式,
(?<Group1>(?!e))ight
Run Code Online (Sandbox Code Playgroud)
然后,您可以从匹配结果中提取组匹配:
match.Groups["Group1"].Captures
Run Code Online (Sandbox Code Playgroud)