user3657339
user3657339

Reputation: 627

Extract value within brackets using regex

Below code works fine, and gives the value within brackets (but i want it to return value WITHOUT bracket, output gives me the value but with bracket)

  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]

Output Expected:

C#.net
Vb.net
ASP.net

Upvotes: 0

Views: 104

Answers (2)

Niranjan Singh
Niranjan Singh

Reputation: 18290

Use m.Groups[1].Value to get the desired values in the foreach loop:

void Main()
{ 

  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.Groups[1].Value);
  }
}

Upvotes: 1

Aprillion
Aprillion

Reputation: 22324

instead of m.Value, use whatever method is used by your undisclosed language to get 1st group, e.g. in C#.NET:

m.Groups[1]

Upvotes: 0

Related Questions