删除富文本框中的额外相邻“空格”

时间:2016-02-25 04:23:01

标签: vb.net richtextbox

如果富文本框的文本包含any,我需要删除1“space”以外的额外相邻“空格”。但代码似乎不起作用。

Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
    For i As Integer = 0 To RichTextBox1.Text.Length - 2
        If RichTextBox1.Text.Chars(i) = " " And RichTextBox1.Text.Chars(i + 1) = " " Then
            RichTextBox1.Text.Replace(RichTextBox1.Text.Chars(i + 1, "")
        End If
    Next

End Sub

1 个答案:

答案 0 :(得分:0)

Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) _
    Handles RichTextBox1.TextChanged
    RichTextBox1.Text = Regex.Replace(RichTextBox1.Text.Trim ,"\s+", " ")
End Sub

测试:

Console.WriteLine(Regex.Replace("The brown        fox  jumped over the  lazy dog      ", "\s+", " "))

输出:

The brown fox jumped over the lazy dog