2012-08-30 131 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]+)