using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace PackingPress.Common
{
    public class RegexHelper
    {
        private RegexHelper(){}

        /// <summary>
        /// 正则表达式替换
        /// </summary>
        /// <param name="input"></param>
        /// <param name="pattern"></param>
        /// <param name="replacement"></param>
        /// <returns></returns>
        public static string Replace(string input, string pattern, string replacement)
        {
            StringBuilder stringBuilder = new StringBuilder(input);
            var matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    if (match.Success)
                    {
                        if (match.Groups.Count > 1)
                        {
                            stringBuilder.Replace(match.Groups[1].Value, replacement);
                        }
                        else
                        {
                            stringBuilder.Replace(match.Value, replacement);
                        }
                    }
                }
            }
            return stringBuilder.ToString();
        }

        public static string MatchSub(string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
        {
            var match = Regex.Match(input, pattern, regexOptions);
            if (match.Success && match.Groups.Count > 1)
            {
                return match.Groups[1].Value;
            }
            return string.Empty;
        }

        public static List<string> MatchSubAll(string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
        {
            List<string> matchesList = new List<string>();
            var matches = Regex.Matches(input, pattern, regexOptions);
            if (matches.Count > 1)
            {
                foreach (Match match in matches)
                {
                    if (match.Success && match.Groups.Count > 1)
                    {
                        matchesList.Add(match.Groups[1].Value);
                    }
                }
            }
            return matchesList;
        }

        public static bool IsMatch(string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
        {
            return Regex.IsMatch(input, pattern, regexOptions);
        }
    }
}