Word文書を開き、クレジットカード番号(さまざまなパターン)をスキャンし、テキストを置き換え、保存して文書を閉じる小さなアプリケーションを作成しています。
私のコードはかなり単純です:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
namespace ParseFilesAndRemoveRegExp
{
class Program
{
static void Main(string[] args)
{
FileManagement m = new FileManagement();
m.OpenSearchAndReplace();
}
}
class FileManagement
{
Word.Application wordapp;
public FileManagement()
{
try
{
wordapp = new Word.Application();
}
catch(Exception ex)
{
if (ex != null)
{
string s = ex.ToString();
}
}
}
internal void OpenSearchAndReplace()
{
object nullobj = System.Reflection.Missing.Value;
try
{
object filename = @"c:\\temp\\document.docx";
object replaceAll = Word.WdReplace.wdReplaceAll;
object matchWildCards = true;
object readOnly = false;
object isVisible = false;
Word.Document doc = wordapp.Documents.Open( ref filename, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
doc.Activate();
wordapp.Selection.Find.ClearFormatting();
//wordapp.Selection.Find.Text = "[0-9]{16}";
wordapp.Selection.Find.Text = "\b(?:[0-9][ -]*?){13,16}\b";
wordapp.Selection.Find.Replacement.ClearFormatting();
wordapp.Selection.Find.Replacement.Text = "---Cardnumber automatically removed---";
wordapp.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj, ref matchWildCards,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref replaceAll, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
doc.Save();
}
catch(Exception ex)
{
string s = ex.ToString();
if( wordapp != null )
{
//wordapp.Documents.Close( ref nullobj, ref nullobj, ref nullobj );
wordapp.Quit( ref nullobj, ref nullobj, ref nullobj );
}
}
}
}
}
ただし、実行すると例外が発生します:「System.Runtime.InteropServices.COMException(0x800A15B8):FindWhatテキストに無効なパターン一致式が含まれています」。
これはWordに送った文字と関係があるのではないかと思ったので、以前は\dを[0-9]と交換していました。しかし、変化はありません。[0-9] {16}で実行すると、1234567891012345が使用したい文字列に置き換えられます。
誰かがここで私を助けることができますか?ドキュメントを管理するために、さまざまな正規表現で検索する必要がありますか、それとも、すでに持っているような1つの単純な正規表現で検索できますか?