? ? ?本文为Aspose.Words使用教程,Aspose.Words是一款先进的文档处理控件,在不使用Microsoft Words的情况下,它可以使用户在各个应用程序中执行各种文档处理任务,其中包括文档的生成、修改、渲染、打印,文档格式转换和邮件合并等文档处理。此外,Aspose.Words支持DOC,OOXML,RTF,HTML,OpenDocument, PDF, XPS, EPUB和其他格式。
? ? 使用范围:在前的范围内替换查找或替换特定的字符串,因为它会返回替换的数量,所以它是在没有替换的条件下搜索字符串是非常有用的。如果一个捕获或替换包含一个或多个特殊字符:段落,细胞破裂,部分断裂,现场开始,字段分隔符、字段,内联图片,绘画对象,脚注的字符串时,会出现异常时。
? ? 在一定的范围内,替代方法提供了几个过载。以下是他们提供的可能性:
?
? ? 下面的例子展示如何使用前面提到的过载。样例类提供的使用了Range.Replace 方法:
?
Example 1: 用一个词换另一个词
?
将所有出现的“sad”替换为“bad”。
?
C#
?
Document doc = new Document(MyDir + @"in.docx");
doc.Range.Replace("sad", "bad", false, true);
?
Visual Basic
?
Dim doc As New Document(MyDir & "Document.doc")
doc.Range.Replace("sad", "bad", False, True)
?
Example 2: 用一个词替换两个相近的词?
?
使用“bad”替换所有“sad”和“mad”。
?
C#
?
Document doc = new Document(MyDir + "Document.doc");
doc.Range.Replace(new Regex("[s|m]ad"), "bad");
?
Visual Basic
?
Dim doc As New Document(MyDir & "Document.doc")
doc.Range.Replace(New Regex("[s|m]ad"), "bad")
?
Example 3:使用一个自定义计数器?
?
如何替换为一个自定义计数器
?
C#
?
public void ReplaceWithEvaluator()
{
? ? Document doc = new Document(MyDir + "Range.ReplaceWithEvaluator.doc");
? ? doc.Range.Replace(new Regex("[s|m]ad"), new MyReplaceEvaluator(), true);
? ? doc.Save(MyDir + "Range.ReplaceWithEvaluator Out.doc");
}
private class MyReplaceEvaluator : IReplacingCallback
{
? ? /// <summary>
? ? /// This is called during a replace operation each time a match is found.
? ? /// This method appends a number to the match string and returns it as a replacement string.
? ? /// </summary>
? ? ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
? ? {
? ? ? ? e.Replacement = e.Match.ToString() + mMatchNumber.ToString();
? ? ? ? mMatchNumber++;
? ? ? ? return ReplaceAction.Replace;
? ? }
? ? private int mMatchNumber;
}
?
Visual Basic
?
Public Sub ReplaceWithEvaluator()
? ? Dim doc As New Document(MyDir & "Range.ReplaceWithEvaluator.doc")
? ? doc.Range.Replace(New Regex("[s|m]ad"), New MyReplaceEvaluator(), True)
? ? doc.Save(MyDir & "Range.ReplaceWithEvaluator Out.doc")
End Sub
Private Class MyReplaceEvaluator
? ? Implements IReplacingCallback
? ? ‘‘‘ <summary>
? ? ‘‘‘ This is called during a replace operation each time a match is found.
? ? ‘‘‘ This method appends a number to the match string and returns it as a replacement string.
? ? Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
? ? ? ? e.Replacement = e.Match.ToString() & mMatchNumber.ToString()
? ? ? ? mMatchNumber += 1
? ? ? ? Return ReplaceAction.Replace
? ? End Function
? ? Private mMatchNumber As Integer
End Class
?
原文:http://18223330727.iteye.com/blog/2237593