简体   繁体   中英

C# RegEx to find values within a string

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"

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.
  }
}

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();
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;

        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM