列表框项目替换

时间:2014-12-01 13:39:41

标签: regex vb.net visual-studio-2010 replace listbox

它会在问号后删除所有列表框项目文本。 但我想反对。因此,请在问号之前替换我的列表框项目文本。

示例列表框项目文本:

 somethingpage?Iwantit

我的代码:

For i = cbox1.Items.Count - 1 To 0 Step -1
     For x = cbox1.Items.Count - 1 To 0 Step -1
         If cbox1.Items(i).ToString.Contains("?") Then
             Dim item = cbox1.Items(i).ToString()
             Dim pos = item.IndexOf("?")
             item = item.Substring(0, pos)
             cbox1.Items(i) = item

         End If
     Next

3 个答案:

答案 0 :(得分:1)

For i As Integer = 0 to cbox1.Items.Count - 1
    Dim sItem As String = cbox1.Items(i).ToString()

    If sItem.Contains("?") Then
        cbox1.Items(i) = sItem.Remove(0, sItem.IndexOf("?"))
    End If
Next

答案 1 :(得分:1)

以下是使用Regex来解决问题的版本......

 Private lstObject As New List(Of Object) 'To hold your values

  Dim oObject As Object

    'Go through changing what we need to and then adding to our list
    For i As Integer = 0 To ListBox1.Items.Count - 1
        oObject = Regex.Replace(CStr(ListBox1.Items(i)), "^(.*?)\?", "", RegexOptions.IgnorePatternWhitespace)
        lstObject.Add(oObject)
    Next

    'If we have items, add them back to the list
    If lstObject.Count > 0 Then
        ListBox1.Items.Clear()
        For i As Integer = 0 To lstObject.Count - 1
            ListBox1.Items.Add(lstObject.Item(i).ToString)
        Next
    End If

答案 2 :(得分:0)

好的,这样就可以毫无错误地完成这项任务:

Dim FormattedString() As String
For i = cbox1.Items.Count - 1 To 0 Step -1
    If cbox1.Items(i).ToString.Contains("?") Then
        Dim item = cbox1.Items(i).ToString()
        FormattedString = Split(item, "?", 2)
        cbox1.Items(i) = FormattedString(0)

    End If
Next
相关问题