侧边栏壁纸
博主头像
怪客のBlog 博主等级

行动起来,活在当下

  • 累计撰写 35 篇文章
  • 累计创建 1 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
C#

C#正则表达式提取两个字符串中间的字符串

怪客
2023-01-17 / 0 评论 / 0 点赞 / 41 阅读 / 0 字

代码

        /// <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=", ";")));

image

0

评论区