filter from listbox regex

488 views Asked by At

I am trying to filter data in a listbox based on an input when I click a filter button.

The lines that are in the list are in this format:

Id: 1 Leefijd patiënt: 12 Gave blood: yes

So my idea was to get each of the lines of the listbox by looping over them. Then using a regex to filter out the number.

Im using 2 regex because if I only filter on number I would get both ID and age (leeftijd).

So my first regex filters out leeftijd: 2x digets and the second one just removes the text and only keeps the number.

Then I do an if statement with if filtertext == final regex then put the whole string we are currently looping over in a new list where the filter is applied.

But somehow the whole thing just doenst work. It works without putting a filter on there just migrating them, but once I try to filter, it breaks.

 private void button1_Click(object sender, EventArgs e)
    {


        string filter = txtFiltered.Text;
        int amountOfItemsInList= lstOrgaandonatie.Items.Count;

        for (int i = 0; i < amountOfItemsInList; i++)
         {

           string line= lstOrgaandonatie.Items[i].ToString();
           string firstFilter= Regex.Match(line, "Leefijd patiënt:+ \\d{2}").Value;
           string finalFilter = Regex.Match(firstFilter, "\\d{2}").Value;



            if (finalFilter== filter )
{
    lsttest.Items.Add(line);
}


           }

    }
1

There are 1 answers

0
AudioBubble On BEST ANSWER

You don't need 2 regex. They can be combined like this -

string filter = "12";
string line = "Id: 1 Leefijd patiënt: 12 Gave blood: yes";

Regex rx = new Regex(@"Leefijd[ ]patiënt:[ ]+(\d+)");
Match _m = rx.Match( line );
if (_m.Success && _m.Groups[1].Value == filter)
{
    Console.WriteLine("Add this to listbox {0} ", line );
}