尝试这样的事情......
static string ReplaceOccurrence(string input, string wordToReplace, string replaceWith, int occToReplace)
{
MatchCollection matches = Regex.Matches(input, string.Format("([\\w]*)", wordToReplace), RegexOptions.IgnoreCase);
int occurrencesFound = 0;
int captureIndex = 0;
foreach (Match matchItem in matches)
{
if (matchItem.Value == wordToReplace)
{
occurrencesFound++;
if (occurrencesFound == occToReplace)
{
captureIndex = matchItem.Index;
break;
}
}
}
if (captureIndex > 0)
{
return string.Format("{0}{1}{2}", input.Substring(0, captureIndex), replaceWith, input.Substring(captureIndex + wordToReplace.Length));
} else
{
return input;
}
}
你将不得不把using System.Text.RegularExpressions;
在顶部。
你的意思是你想要编写在Word文档(如宏)中执行的代码,或者你想要在修改Word文档的服务器上执行代码吗? – 2011-05-13 10:08:00
其实我想在http://www.codeproject.com/KB/edit/Application_to_Word.aspx的方式。此链接提供了如何替换一个并全部替换。所以我想这样,这就是我需要的 – 2011-05-13 10:36:21