I want to remove some rows in a listbox using regex.
the rows contains the regex pattern has to be removed
Listbox.addrow "«ab1"
Listbox.addrow "000"
Listbox.addrow "«ab0"
Listbox.addrow "L000"
dim row as integer
for row=0 to Listbox1.ListCount -1
dim rx1 as new RegEx
rx1.SearchPattern = "^.*\b(000|ab1|ab0|L)\b.*$"
dim match1 as RegExMatch = rx1.Search((Listbox1.Cell(row,0)))
if match1 is nil then
else
Listbox1.RemoveRow row
end if
next
Var oRegEx As New RegEx
Var oMatch As RegExMatch
oRegEx.SearchPattern = ".*\b(000|ab1|ab0|L)\b.*"
For iRow As Integer = Listbox1.LastRowIndex DownTo 0
oMatch = oRegEx.Search(Listbox1.CellValueAt(iRow, 0))
If Not (oMatch Is Nil) Then
Listbox1.RemoveRowAt(iRow)
End If
Next
By the way, your code upstairs works. From your description it’s hard to see what exactly the result should be after the loop in the Listbox.
Pattern is row: “^0\d*$”
Pattern is at beginning of row: “^0\d*”
Pattern is in row: “0\d*” (but that allows L0056xat)
Pattern is word in row: “\b0\d*\b”
^ beginning of line
0 Followed by a zero
\d* Followed by numbers
$ End of line
\b word boundary
For i = ListBox1.Ubound DownTo 0
If Not Match then
LB.removeRow row
End if
Next i
You’re right, I should have looked harder at the pattern rather than copy-and-pasting it. In my defense, I was focussed on the major problem we both saw of working the rows backwards.
I agree that InStr (or IndexOf) will be better in many cases, but not this one. This pattern is not “contains one of these strings”, but “contains one of these words”, a big difference, and one that is hard to emulate.
For example, you said
but this pattern wouldn’t match that whereas a simple InStr would.
To clarify Markus’ advice, if the list of the what you want to keep is shorter than the what you want to remove, match on that and remove whatever doesn’t match.