我是RegEx的新手。我有一个像下面这样的字符串。我想获得[{##}]
之间的值例如:"Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]"
我想从上面的字符串中获取以下值。
"John",
"ABC Bank",
"Houston"
答案 0 :(得分:1)
根据解决方案和awesome breakdown for matching patterns inside wrapping patterns,您可以尝试:
\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]
\[\{\#
是[{#
和\#\}\]
的转义序列,#}]
的转义结束序列。
您的内部值位于名为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.
}
}
答案 1 :(得分:0)
基于解决方案Regular Expression Groups in C#。 你可以试试这个:
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();
答案 2 :(得分:-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;
}
}
}