Reputation: 143
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"
Upvotes: 4
Views: 28312
Reputation: 258
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();
Upvotes: 9
Reputation: 15579
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.
}
}
Upvotes: 1
Reputation: 28
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;
}
}
}
Upvotes: -2