Home > Software engineering >  Retain first original character when using Regex Replace?
Retain first original character when using Regex Replace?

Time:02-24

Here is VB.Net Regex code to replace text unless that text is preceeded or followed by a letter:

Imports System
Imports System.Text.RegularExpressions
​
Public Module Module1

Public Sub Main()

Dim strProhibitedWord As String = "fox"
Dim strProhibitedWordEnclosed As String = "(?<!\p{L})"   strProhibitedWord   "(?!\p{L})"
Dim strSentence1 As String = "The quick brown Fox jumped over the foxy sheep to see his fox friend."
Dim optOptions1 As RegexOptions = RegexOptions.IgnoreCase
Dim strResult As String = Regex.Replace(strSentence1, strProhibitedWordEnclosed, "***", optOptions1)

Console.WriteLine(strResult)

End Sub

End Module

The code gives the result:

The quick brown *** jumped over the foxy sheep to see his *** friend.

What code change could give the following result (e.g., show the first original character followed by the remaining character mask):

The quick brown F** jumped over the foxy sheep to see his f** friend.

CodePudding user response:

You can wrap the first word letter with a capturing group:

Dim strProhibitedWordEnclosed As String = "(?<!\p{L})(" & strProhibitedWord.Substring(0,1) & ")" & strProhibitedWord.Substring(1) & "(?!\p{L})"

Then, you need to replace with $1**:

Dim strResult As String = Regex.Replace(strSentence1, strProhibitedWordEnclosed, "$1**", optOptions1)

See the VB.NET demo online:

Imports System
Imports System.Text.RegularExpressions
 
Public Class Test
    Public Shared Sub Main()
        Dim strProhibitedWord As String = "fox"
        Dim strProhibitedWordEnclosed As String = "(?<!\p{L})(" & strProhibitedWord.Substring(0,1) & ")" & strProhibitedWord.Substring(1) & "(?!\p{L})"
        Dim strSentence1 As String = "The quick brown Fox jumped over the foxy sheep to see his fox friend."
        Dim optOptions1 As RegexOptions = RegexOptions.IgnoreCase
        Dim strResult As String = Regex.Replace(strSentence1, strProhibitedWordEnclosed, "$1**", optOptions1)
 
        Console.WriteLine(strResult)
    End Sub
End Class

Output:

The quick brown F** jumped over the foxy sheep to see his f** friend.
  • Related