我正在创建一个小型应用程序,它将打开一个 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): Find What 文本包含无效的模式匹配表达式”。
我认为这可能与我发送到 Word 的字符有关,因此我之前将 \d 与 [0-9] 交换。但没有变化。如果我使用 [0-9]{16} 运行,它会将 1234567891012345 替换为我要使用的字符串。
有谁可以帮我离开这里吗?我是否必须使用许多不同的正则表达式来搜索来管理文档,或者这可以通过一个简单的正则表达式来完成,就像我已经拥有的一样?