我使用這個庫來實現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。
顯然第一行需要修改,但我不確定如何精確修改它。
這樣的作品,謝謝;但它意味着引用包含在捕獲中(即'MERGEFIELD「foo」'具有'name = \「foo \」'而不是'name = foo')。有沒有辦法排除他們? – Dai
嘗試將'?''移動到指定組的外部 –
我嘗試了您的更新版本,但出現錯誤:「嵌套量詞」。 * MERGEFIELD [\ s] +「?(? [#\ w] *)」?{1}' –
Dai