Aspose word实现文本,字符查找和替换功能
Aspose word是一款功能强大的word处理控件,支持word的创建、编辑、修改、删除、转换等功能,这里咱们简单介绍Aspose word如何实现替换和查找功能,通常控件提供的 Range.Replace方法可以进行下面几种替换:
1. 指定一个字符串用于查找和替换
2. 可以指定一个正则表达式,用于查找匹配的字符串并且替换
事例1.
该事例主要是实现替换文档里的所有"sad"字符为"bad"字符
C#
Document doc = new Document(MyDir + "Document.doc");
doc.Range.Replace("sad", "bad", false, true);
Visual Basic
Dim doc As New Document(MyDir & "Document.doc")
doc.Range.Replace("sad", "bad", False, True)
事例2:
该事例主要是实现替换文档里的所有"sad"或"mad"字符串为"bad"
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")
事例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.
''' </summary>
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