Search code examples
c#regexparentheses

Extract string in parentheses using c#


I have a string ---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---

I want to get the value within the [] (i.e. 1508825516987)

How can I get the value using Regex?


Solution

  • Explanation:

    • \[ : [ is a meta char and needs to be escaped if you want to match it literally.
    • (.*?) : match everything in a non-greedy way and capture it.
    • \] : ] is a meta char and needs to be escaped if you want to match it literally.

    Source of explanation: Click

    static void Main(string[] args)
    {
        string txt = "---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---";
    
        Regex regex = new Regex(@"\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
        Match match = regex.Match(txt);
        if (match.Success)
        {
            for (int i = 1; i < match.Groups.Count; i++)
            {
                String extract = match.Groups[i].ToString();
                Console.Write(extract.ToString());
            }
        }
        Console.ReadLine();
    }
    

    Links to learn to create regular expressions:

    Update 1:

    Regex regex = new Regex(@"^---.*\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    
    • ^ is start of string
    • --- are your (start) characters
    • .* is any char between --- and [