4

I am new to RegEx. I have a string like following. I want to get the values between [{# #}]

Ex: "Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]"

I would like to get the following values from the above string.

"John",
"ABC Bank",
"Houston"
Andrew
  • 7,602
  • 2
  • 34
  • 42
Satya Sahoo
  • 143
  • 1
  • 2
  • 9

3 Answers3

9

Based on the solution Regular Expression Groups in C#. You can try this:

       string sentence = "Employee name is [{#john#}], works for [{#ABC BANK#}], 
        [{#Houston#}]";
        string pattern = @"\[\{\#(.*?)\#\}\]";

        foreach (Match match in Regex.Matches(sentence, pattern))
        {
            if (match.Success && match.Groups.Count > 0)
            {
                var text = match.Groups[1].Value;
                Console.WriteLine(text);
            }
        }
        Console.ReadLine();
Sunita
  • 258
  • 1
  • 5
  • 10
1

Based on the solution and awesome breakdown for matching patterns inside wrapping patterns you could try:

\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]

Where \[\{\# is your escaped opening sequence of [{# and \#\}\] is the escaped closing sequence of #}].

Your inner values are in the matching group named Text.

string strRegex = @"\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
string strTargetString = @"Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    var text = myMatch.Groups["Text"].Value;

    // TODO: Do something with it.
  }
}
Reddog
  • 15,219
  • 3
  • 51
  • 63
-2
using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Test("the quick brown [{#fox#}] jumps over the lazy dog."));
            Console.ReadLine();
        }

        public static string Test(string str)
        {

            if (string.IsNullOrEmpty(str))
                return string.Empty;


            var result = System.Text.RegularExpressions.Regex.Replace(str, @".*\[{#", string.Empty, RegexOptions.Singleline);
            result = System.Text.RegularExpressions.Regex.Replace(result, @"\#}].*", string.Empty, RegexOptions.Singleline);

            return result;

        }

    }
}
Sherwin
  • 28
  • 2