代码
/// <summary>
/// 正则表达式提取两个字符串中间的字符串
/// </summary>
/// <param name="input">待提取的字符串</param>
/// <param name="begin">开头</param>
/// <param name="end">结尾</param>
/// <param name="includeBegin">是否包含开头</param>
/// <param name="includeEnd">是否包含结尾</param>
/// <returns></returns>
public static List<string> ExtractStringBetweenBeginAndEnd(string input, string begin, string end,bool includeBegin=false,bool includeEnd=false)
{
var result = new List<string>();
string pattern;
if (includeBegin)
{
if (includeEnd)
{
pattern = string.Format(@"{0}.*?{1}", begin, end);
}
else
{
pattern = string.Format(@"{0}.*?(?={1})", begin, end);
}
}
else
{
if (includeEnd)
{
pattern = string.Format(@"(?<={0}).*?{1}", begin, end);
}
else
{
pattern = string.Format(@"(?<={0}).*?(?={1})", begin, end);
}
}
Regex regex = new Regex(pattern);
foreach (Match match in regex.Matches(input))
{
if (match != null && !string.IsNullOrEmpty(match.Value))
{
result.Add(match.Value);
}
}
return result;
}
测试
var str = "{Name=张三;Name=李四;}";
Console.WriteLine(string.Join(Environment.NewLine, ExtractStringBetweenBeginAndEnd(str, "Name=", ";")));
评论区