我正在使用这个库在我的应用程序中实现Word文档邮件合并:http://www.codeproject.com/Articles/38575/Fill-Mergefields-in-docx-Documents-without-Microso
它工作得很好,但后来我对代码进行了大量重构,并执行了其他任务,以便将其与我自己的应用程序集成。
该库使用此正则表达式来捕获Word邮件合并字段:
private static readonly Regex _instructionRegEx = new Regex(
@"^[\s]*MERGEFIELD[\s]+(?<name>[#\w]*){1} # This retrieves the field's name (Named Capture Group -> name)
[\s]*(\\\*[\s]+(?<Format>[\w]*){1})? # Retrieves field's format flag (Named Capture Group -> Format)
[\s]*(\\b[\s]+[""]?(?<PreText>[^\\]*){1})? # Retrieves text to display before field data (Named Capture Group -> PreText)
[\s]*(\\f[\s]+[""]?(?<PostText>[^\\]*){1})? # Retrieves text to display after field data (Named Capture Group -> PostText)",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline
);这捕获了像MERGEFIELD FieldNameGoesHere这样的示例,但是我遇到过字段名称被双引号括起来的示例,比如MERGEFIELD "FieldNameGoesHere",但是正则表达式没有捕获这些字段名。
正如您所看到的,正则表达式有点硬核,我当前的regex-fu不能修改它以使用双引号,但也接受未引用的MERGEFIELD。
显然,第一行需要修改,但我不确定如何准确地修改它。
发布于 2012-08-31 06:52:58
更新:将双引号移到命名组的外部。
在第一行中,将(?<name>[#\w]*)替换为"?(?<name>[#\w]*)"?。"?让RegEx查找可选的双引号。
发布于 2016-09-01 18:25:51
^[\s]*MERGEFIELD[\s]+"?(?<name>[#\w]*){1}"?如果字段名包含空格: MERGEFIELD "My field Name“,则不起作用。
可以使用:
MERGEFIELD\s+"(.*?)"或
MERGEFIELD\s+([#\w]+) https://stackoverflow.com/questions/12206667
复制相似问题