Back to Devexpress

How to: Use Regular Expressions to Search and Replace Text Strings

officefileapi-120430-word-processing-document-api-examples-search-and-replace-how-to-use-regular-expressions-to-search-and-replace-text-strings.md

latest1.7 KB
Original Source

How to: Use Regular Expressions to Search and Replace Text Strings

  • Sep 19, 2023

The SubDocument.ReplaceAll method allows you to search and replace specific text strings using Regular Expressions.

This example shows how to use this method to change US formatted dates (moth/day/year) in the document to European format (year-month-day and day.month.year).

csharp
Document document = richEditDocumentServer1.Document;
document.AppendText("12\\14\\2014" + Environment.NewLine);
string pattern = @"(?<mm>\d{2}).(?<dd>\d{2}).(?<yyyy>\d{4})";
string replacementString = @"${yyyy}-${mm}-${dd} or ${dd}.${mm}.${yyyy}";
System.Text.RegularExpressions.Regex myRegEx = new System.Text.RegularExpressions.Regex(pattern);
int count = document.ReplaceAll(myRegEx, replacementString);
System.Windows.Forms.MessageBox.Show(String.Format("We've done {0} replacement(s).", count));
vb
Private Sub SurroundingSub()
    Dim document As Document = richEditDocumentServer1.Document
    document.AppendText("12\14\2014" & Environment.NewLine)
    Dim pattern As String = "(?<mm>\d{2}).(?<dd>\d{2}).(?<yyyy>\d{4})"
    Dim replacementString As String = "${yyyy}-${mm}-${dd} or ${dd}.${mm}.${yyyy}"
    Dim myRegEx As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(pattern)
    Dim count As Integer = document.ReplaceAll(myRegEx, replacementString)
    System.Windows.Forms.MessageBox.Show(String.Format("We've done {0} replacement(s).", count))
End Sub