How to get matched string from Regex? [C#]

13,769

Solution 1

Use Regex.IsMatch method to check if regular expression finds a match in the input string. E.g

    foreach (var item in selectedItems)
    {
         if (filter.IsMatch(item.ToString())
             // matched
    }

BTW Keep in mind that [0-9]* will match anything, because you don't require any numbers to be in input string. Possibly you need ^\d+$

UPDATE: Getting matched number:

Regex filter = new Regex(@"(\d+)");

foreach (var item in checkedListBox1.CheckedItems)
{
    var match = filter.Match(item.ToString());
    if (match.Success)
    {
        MessageBox.Show(match.Value);
    }    
}

Solution 2

To find all matches you need to use .Matches() and iterate the returned collection.

Another good practice is to compile your regular expressions so you will not take a performance hit every time it is executed, to do so assign it to a static field in you class and use "RegexOptions.Compiled".

Here's a small example, which can easily be modified to support your scenario:

class Program {
    private static Regex _filterRegex = new Regex(@"[0-9]+", RegexOptions.Compiled);

    static void Main(string[] args) {
      foreach (Match match in _filterRegex.Matches("1,2,3,4,5,6")) {
        Console.WriteLine("Match: " + match.Value);
      }
    }
  }
Share:
13,769
Billie
Author by

Billie

Updated on June 07, 2022

Comments

  • Billie
    Billie almost 2 years

    I have the following code:

    private void button_borrow_Click(object sender, EventArgs e)
        {
            Regex filter = new Regex(@"[0-9]*");
            String items = "";
            var selectedItems = checkedListBox_bookview.CheckedItems;
            foreach (var item in selectedItems)
            {
    
            }
            MessageBox.Show(items.ToString() + " Were selected: " + selectedItems.Count);
        }
    

    I want to get the matched Strings from filter. how do I do so?

  • Billie
    Billie about 11 years
    How do I get the metched string? I mean I have "xxaajj8589jfa". I want just 8589