我正在尝试在电子邮件中查找未使用的合并字段并抛出解析器不支持的字段。格式为 [合并字段]。括号内的所有大写字母。
然后我想在文本中抛出第一个不受支持的合并字段的值。
if (Regex.IsMatch(email.Body, @"[[A-Z]+]"))
{
var regexobj = new Regex(@"[[A-Z]+]");
var regexBody = regexobj.Match(email.Body).Groups[1].Value;
throw new NotImplementedException("Unsupported Merge Field:"+ regexBody );
}
现在我收到异常,但只有消息是"不支持的合并字段:"
您正在尝试获取(捕获)组 1(括号中的匹配内容)的值,该值在您的表达式中不存在。
也许你想改用这样的表达式:
[([A-Z]+)]
您需要使用括号才能捕获。
http://www.regular-expressions.info/refadv.html
另请参阅 http://msdn.microsoft.com/en-us/library/az24scfc.aspx
我喜欢使用格式为(?<名称>子表达式),这将允许您按名称而不是按索引访问捕获。名称>
如下所示(手工编码)
if (Regex.IsMatch(email.Body, @"[[A-Z]+]"))
{
var regexobj = new Regex(@"(?<unsupportedField>[[A-Z]+])");
foreach(Match match in regexobj.Matches(email.Body))
{
string unsupported = match.Groups["unsupportedField"].Value
//aggregate these then throw
}
throw new NotImplementedException("Unsupported Merge Field:"+ regexBody );
}