Hello all, I am new to regex and need some help with my current code. Below's the code I am using and results I am seeing. What I want is for it to match just the line where it sees "ID:". Would be great if I can get pointers on how to accomplish that. Thanks!

Regex idRegex = new Regex(@"ID: \s*(.*)");

                    if (idRegex.IsMatch(searchRange))
                    {                        
                        Match idMatch = idRegex.Match(searchRange);
                        id = idMatch.Groups[1].Value;
                        id = id.Trim();
                    }

// Below's how my searchRange looks like :-

Some random text
ID: test@test.com

---------------------Random Text -------------------------------

Results - ID:

---------------------Random Text -------------------------------


Expected - Don't need anything below the ID line. How do I match just one line. Tried RegexOptions.Singleline but got the same results.

You want to use the static Regex.Match() if you run this iteration more than once in the lifecycle of the applicaiton.

The Regex class contains several static (or Shared in Visual Basic) methods that allow you to use a regular expression without explicitly creating a Regex object. In the .NET Framework version 2.0, regular expressions compiled from static method calls are cached, whereas regular expressions compiled from instance method calls are not cached. By default, the regular expression engine caches the 15 most recently used static regular expressions. As a result, in applications that rely extensively on a fixed set of regular expressions to extract, modify, or validate text, you may prefer to call these static methods rather than their corresponding instance methods. Static overloads of the IsMatch, Match, Matches, Replace, and Split methods are available.

The ^ is the begging of line code and .+ matches a character after :. So this line means "It must be ID: at the beginning of line and have at least one character after the colon"

private void button1_Click(object sender, EventArgs e)
    {
      const string regex = @"^ID:.+";
      List<string> data = new List<string>();
      data.Add("some random text");
      data.Add("ID: sk@sk.com");
      data.Add("data ID: dont match");
      if (System.Text.RegularExpressions.Regex.Match(data[0], regex).Success)
        throw new Exception("should not have matched");
      if (!System.Text.RegularExpressions.Regex.Match(data[1], regex).Success)
        throw new Exception("should have matched");
      if (System.Text.RegularExpressions.Regex.Match(data[2], regex).Success)
        throw new Exception("should not have matched");
    }
This question has already been answered. Start a new discussion instead.