正则表达式提取月份

        /// <summary>
        /// 从字符串中获取月份(MM,2位数字)
        /// </summary>
        /// <returns></returns>
        public static string GetMonth(string str)
        {
            string result = string.Empty;

            string pattern = @"(.*)((\d{4})\.(\d{1,2}))(.*)";
            string replacement = "$1$4$5";
            string newShortName = Regex.Replace(str, pattern, replacement);

            Regex regYf = new Regex(@"\D?(\d{1,})\D");
            Match m = regYf.Match(newShortName);
            if (null != m)
            {
                string yf = m.Groups[1].Value;
                result = yf.PadLeft(2, '0');
                if (yf.Length == 6)
                    result = yf.Substring(4, 2);
                else if (yf.Length <= 2)
                    result = yf.PadLeft(2, '0');
                else
                    result = yf;
            }
            else
            {
                result = string.Empty;
            }
            return result;
        }

        /// <summary>
        /// 从字符串中获取月份(MM,2位数字)
        /// </summary>
        /// <returns></returns>
        public static string GetMonth(string str)
        {
            //期间:2018年01月 币种:人民币 单位:元
            string pattern = @"(.*)(\d{4})(年)(\d{1,2})(月)(.*)";
            string replacement = "$2$4";
            string newShortName = Regex.Replace(str, pattern, replacement);

            Regex reg = new Regex(@"\d{6}");
            if (!reg.IsMatch(newShortName))
            {
                return "";
            }
            return newShortName;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_42678477/article/details/81430129