News Category

Replace Text with Regular Expression (Regex) in PowerPoint in C#, VB.NET

2021-08-23 07:49:36 Written by  support iceblue
Rate this item
(0 votes)

Spire.Presentation for .NET provides you with the ability to replace text with regular expression using the ReplaceTextWithRegex method of IShape class. The ReplaceTextWithRegex method accepts the following parameters:

Regex: the regular expression to search text.

string: the text to replace with.

The following example demonstrates how to replace text with regular expression in a PowerPoint document using Spire.Presentation for .NET.

C#
using Spire.Presentation;
using System.Text.RegularExpressions;

namespace ReplaceTextWithRegex
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation instance
            Presentation ppt = new Presentation();
            //Load a sample document
            ppt.LoadFromFile("Sample.pptx");

            //Get the first slide
            ISlide slide = ppt.Slides[0];

            //Replace "ABC" and the subsequent to the end of the line as "ABC DEF"
            Regex regex = new Regex("ABC.*");
            string newvalue = "ABC DEF";
            foreach (IShape shape in slide.Shapes)
            {
                shape.ReplaceTextWithRegex(regex, newvalue);
            }

            //Save the result document
            ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013);
        }
    }
}
VB.NET
Imports Spire.Presentation
Imports System.Text.RegularExpressions

Namespace ReplaceTextWithRegex
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Presentation instance
            Dim ppt As Presentation = New Presentation()
            'Load the sample document
            ppt.LoadFromFile("Sample.pptx")

            'Get the first slide
            Dim slide As ISlide = ppt.Slides(0)

            'Replace "ABC" and the subsequent to the end of the line as "ABC DEF"
            Dim regex As Regex = New Regex("ABC.*")
            Dim newvalue As String = "ABC DEF"

            For Each shape As IShape In slide.Shapes
                shape.ReplaceTextWithRegex(regex, newvalue)
            Next

            'Save the result document
            ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013)
        End Sub
    End Class
End Namespace

The input PowerPoint document:

Replace Text with Regular Expression (Regex) in PowerPoint in C#, VB.NET

The output PowerPoint document:

Replace Text with Regular Expression (Regex) in PowerPoint in C#, VB.NET

Additional Info

  • tutorial_title:
Last modified on Friday, 24 September 2021 09:17