【发布时间】:2011-01-15 04:14:47
【问题描述】:
我正在创建一个小型应用程序,它将打开一个 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 替换为我要使用的字符串。
有人可以帮我吗?我是否必须使用许多不同的正则表达式来搜索来管理文档,或者这可以使用一个简单的正则表达式来完成,就像我已经拥有的一样?
【问题讨论】:
-
我很好奇你会在扫描信用卡号码时获得多少帮助......(不是我的反对票)
-
让我这样说 - 我的客户有数千份文档和电子邮件,其中包含卡号。这是一个安全风险。所以我将不得不再次打开、搜索、删除和关闭。
-
该死的——这是怎么发生的?我会关门的。
-
这比一棵 100 年的橡树还要阴暗。
标签: regex ms-word credit-card