Find and replace text in a document using Aspose.Words tutorial

     This article is a tutorial for using Aspose.Words, an advanced document processing control that enables users to perform various document processing tasks in various applications without using Microsoft Words, including document generation , editing, rendering, printing, document processing such as document format conversion and mail merge. Furthermore, Aspose.Words supports DOC, OOXML, RTF, HTML, OpenDocument, PDF, XPS, EPUB and other formats.

    Use Range:Replace in the previous range to find or replace a specific string, because it will return the number of replacements, so it is very useful to search for strings without replacement. An exception occurs when a capture or replace string contains one or more special characters: paragraph, cell break, section break, field start, field separator, field, inline picture, paint object, footnote.

    To a certain extent, the alternative method provides several overloads. Here are the possibilities they offer:

 

  • You can specify a string to be replaced, and once replaced, all of this string will be replaced, whether the replacement is case-sensitive, or only individual words will be affected. Note that a word is defined as consisting of only alphanumeric characters. If the replacement is only performed on the entire word matched, and the input string contains symbols, then the word will not be searched.
  • You can pass a regex pattern for finding matches and a string, and then replace them. This overload substitution captures the entire match via a regular expression.
  • You can implement the [{{ IReplacingCallback }}] interface with a regular expression pattern and an object. This presents a user-defined method that evaluates the replacement at each step, and you can also indicate whether the replacement should be in a forward or backward direction. It is recommended that if a node is to be removed during the replacement process then the replacement should be performed backwards to avoid any potential problems that may arise with removing the node during the replacement process. A class implementing the callback interface will define a [IReplacingCallback.Replacing] method that accepts [{ { ReplacingArgs } }] objects that provide custom replacement data operations. This method should return a [{ { ReplaceAction } }] enumeration value specifying what happened during the replacement operation for the current match - whether it should be replaced, skipped, or the entire replacement operation should terminate.

    The following example shows how to use the aforementioned overloads. The sample class provided uses the Range.Replace method:

 

  • Example 1 Replace all occurrences of "sad" with "bad".
  • Example 2 Replace all occurrences of "sad" or "mad" with "bad".
  • Example 3 Use the substitution evaluation method to concatenate occurrences of the word "sad" or "bad", increasing the count for each occurrence.

Example 1: Swap one word for another

 

Replace all occurrences of "sad" with "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: Replace two similar words with one word 

 

Replace all "sad" and "mad" with "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")

 

Example 3: Using a custom counter 

 

How to replace with a custom counter

 

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

 

Check out more Aspose.Words tutorials

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326898941&siteId=291194637