嘗試這樣的事情......
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