2012-08-30 137 views
0

我使用这个库来实现Word文档邮件合并在我的应用程序在Word MERGEFIELD正则表达式: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"然而,正则表达式不捕获这些。

正如你所看到的,正则表达式有点硬核,超出了我目前的正则表达式-fu来修改它使用双引号,但也接受未引用的MERGEFIELDs。

显然第一行需要修改,但我不确定如何精确修改它。

回答

1

更新:将双引号移至指定组的外部。

在您的第一行中,将(?<name>[#\w]*)替换为"?(?<name>[#\w]*)"? 已将RegEx替换为可选的双引号。

+0

这样的作品,谢谢;但它意味着引用包含在捕获中(即'MERGEFIELD“foo”'具有'name = \“foo \”'而不是'name = foo')。有没有办法排除他们? – Dai

+0

尝试将'?''移动到指定组的外部 –

+0

我尝试了您的更新版本,但出现错误:“嵌套量词”。 * MERGEFIELD [\ s] +“?(? [#\ w] *)”?{1}' – Dai

0
^[\s]*MERGEFIELD[\s]+"?(?<name>[#\w]*){1}"? 

如果字段名称包含空格不起作用: MERGEFIELD“我的字段名称”。

可用于:

MERGEFIELD\s+"(.*?)" 

MERGEFIELD\s+([#\w]+)