C# Regular Expression Get Text Between Brackets

C# Regular Expression Get Text Between Brackets

Regular expression get text inside square brackets. You want to get string inside the square bracket. Here is very short example of how to do that using C#.net and VB.net.

using System;
using System.Text.RegularExpressions;

namespace Csharp.BracketText.Example
{
  class Program
  {
    static void Main(string[] args)
    {

      string regularExpressionPattern = @"\[(.*?)\]";

      string inputText = "Find string inside brackets [C#.net] and [Vb.net] example.";

      Regex re = new Regex(regularExpressionPattern);

      foreach (Match m in re.Matches(inputText))
      {
        Console.WriteLine(m.Value);
      }

      Console.ReadLine();

    }
  }
}

Output.

[C#.net]
[Vb.net]
[ASP.net]

VB.net Regular expression to get string inside brackets.

Imports System
Imports System.Text.RegularExpressions

Namespace Csharp.BracketText.Example
	Class Program
		Private Shared Sub Main(args As String())

			Dim regularExpressionPattern As String = "\[(.*?)\]"

			Dim inputText As String = "Find string inside brackets [C#.net] and [Vb.net] example in [ASP.net]."

			Dim re As New Regex(regularExpressionPattern)

			For Each m As Match In re.Matches(inputText)
				Console.WriteLine(m.Value)
			Next

			Console.ReadLine()

		End Sub
	End Class
End Namespace

Note: To use Regular expression in .net, you need to use System.Text.RegularExpression namespace.

How to get text inside left and right angles < >.

You can refer the same examples and use the regular expression pattern explained below.
string regularExpressionPattern = @"\<(.*?)\>";

      string inputText = "Find string inside brackets <C#.net> and <Vb.net> example in [ASP.net].";

      Regex re = new Regex(regularExpressionPattern);

      foreach (Match m in re.Matches(inputText))
      {
        Console.WriteLine(m.Value);
      }
Output.

<C#.net>
<Vb.net>

You may want to get text from curly brackets { }or parenthesis ( ).

string regularExpressionPattern = @"\((.*?)\)";

     string inputText = "Find string inside brackets (C#.net) and <Vb.net> example in [ASP.net].";

     Regex re = new Regex(regularExpressionPattern);

     foreach (Match m in re.Matches(inputText))
     {
       Console.WriteLine(m.Value);
     }
Output
(C#.net)
string regularExpressionPattern = @"\{(.*?)\}";

     string inputText = "Find string inside brackets (C#.net) and {Vb.net} example in [ASP.net].";

     Regex re = new Regex(regularExpressionPattern);

     foreach (Match m in re.Matches(inputText))
     {
       Console.WriteLine(m.Value);
     }
Output {Vb.net}

Tags: