我在替換字串中的數字時遇到問題。
代碼是:
Dim Searchstring As String= "2 7 12 33 4 15 22 30 15"
Dim Pattern As String= "^([0-9]$)"
Dim Match As String = Val(TextBox1.Text)
Dim ReplacementString As String = "0"
Dim rgx As Regex = New Regex(pattern)
Dim NewString As String
NewString = Regex.Replace(Searchstring, Match, ReplacementString)
RichTextBox2.Text = NewString
問題是當我在文本框中輸入一個數字,比如“2”并運行程式時,richtextbox2.text 中的替換將如下所示:0 7 10 33 4 15 00 30 15 而不是 0 7 12 33 4 15 22 30 15
但是當我輸入“22”或“12”的數字時,只有這些數字會被替換,這沒關系。
那么,如果我想要并且僅替換數字“2”而不更改“12”或“22”,我該如何找到一個僅替換數字“2”的模式?
請問你能幫我處理這個案子嗎?
uj5u.com熱心網友回復:
適當的模式是^([0-9] )獲取第一個數字并將它們替換為 0。實際上,這個 '$' 字符表示字串的結尾。如果您只需要替換第一個數字,它不應該在那里。
' ' 字符表示“前一個模式中的一個或多個”,然后它將從文本開頭搜索“[0-9]”范圍內的一個或多個數字并僅捕獲數字。
uj5u.com熱心網友回復:
您需要告訴它如何分隔要替換的專案,在這種情況下,“單詞邊界”* 物體\b將起作用:
Dim searchstring As String = "2 7 12 33 4 15 22 30 15"
Dim match As String = TextBox1.Text
Dim pattern = "\b" & Regex.Escape(match) & "\b"
Dim rgx As Regex = New Regex(pattern)
Dim replacementString As String = "0"
Dim newString = rgx.Replace(searchstring, replacementString)
RichTextBox2.Text = newString
我
當您告訴它時,它會替換兩次出現的“15”:

*什么是正則運算式中的單詞邊界?
uj5u.com熱心網友回復:
要查找字串中的任何數字,您可以使用\b來表示單詞的開頭或結尾(即,字母、數字和下劃線的序列)。
示例:僅替換數字 12:
\b12\b
這不會取代,例如,在123或中412。
uj5u.com熱心網友回復:
雖然我不會不同意已經提出的答案,但我會斷言最簡單和最明顯的選擇是使用內置的 .NET 方法來操作您的字串。
您的輸入是一個字串,其中包含由空格分隔的數字。然后,您想用一些替換替換精確的數字匹配。
您可以通過拆分字串、遍歷陣列、修改與您的值匹配的當前迭代項,然后將它們連接回來來做到這一點:
Dim searchString As String = "2 7 12 33 4 15 22 30 15"
Dim replacementString As String = "0"
If (Not Integer.TryParse(TextBox1.Text, Nothing)) Then
MessageBox.Show("Please enter a valid integer.")
Return
End If
Dim searchStringCollection() As String = searchString.Split(" "c)
For index As Integer = 0 To searchStringCollection.Length - 1
If (searchStringCollection(index) = TextBox1.Text) Then
searchStringCollection(index) = replacementString
End If
Next
Dim newString As String = String.Join(" ", searchStringCollection)
小提琴:https ://dotnetfiddle.net/dZfsy6
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410500.html
標籤:
