這是用于替換文本的 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.
uj5u.com熱心網友回復:
您可以使用捕獲組包裝第一個單詞字母:
Dim strProhibitedWordEnclosed As String = "(?<!\p{L})(" & strProhibitedWord.Substring(0,1) & ")" & strProhibitedWord.Substring(1) & "(?!\p{L})"
然后,您需要替換為$1**:
Dim strResult As String = Regex.Replace(strSentence1, strProhibitedWordEnclosed, "$1**", optOptions1)
在線查看VB.NET 演示:
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
輸出:
The quick brown F** jumped over the foxy sheep to see his f** friend.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432360.html
上一篇:無順序地將元素串列與字串匹配
