Loading ...

C# Regex: Extract the text between square brackets, without returning the brackets themselves. | CodeAsp.Net

C# Regex: Extract the text between square brackets, without returning the brackets themselves.

 /5
0 (0votes)

In this blog I will show you how to extract the text between square brackets, without returning the brackets themselves.  I will use REGEX class of in order to do so. Let's assume we have a string "Are you ready for regex [test text] magic?" and we want to extract "test text" from it ie. the text which lies in between the square brackets. Below is the sample code for it:

using System.Text.RegularExpressions;

namespace Sample.Console
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string input = "Are you ready for regex [test text] magic?";
            string pattern = @"(?<=\[)(.*?)(?=\])";
            Match output = Regex.Match(input, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            System.Console.WriteLine(output);
            System.Console.ReadLine();
        }

    }
}

Output:

Explanation of regex pattern used above:

(?<=\[)(.*?)(?=\])

Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\[)»
Match the character “[” literally «\[»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\])»
Match the character “]” literally «\]»


Created with RegexBuddy


Do let me know your feedback, comments. 

Comments (no comments yet)

Top Posts