使用正则表达式替换时保留第一个原始字符?

Retain first original character when using Regex Replace?

这里是 VB.Net 替换文本的正则表达式代码,除非该文本前面或后面有字母:

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 quick brown *** jumped over the foxy sheep to see his *** friend.

更改什么代码可以得到以下结果(例如,显示第一个原始字符,然后显示剩余的字符掩码):

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

您可以用捕获组包裹第一个单词字母:

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

然后,您需要替换为**

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

查看 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, "**", optOptions1)
 
        Console.WriteLine(strResult)
    End Sub
End Class

输出:

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