C#实用扩展方法整理收集

using System;
using System.Text.RegularExpressions;

namespace mzwu_com
{
    static class Extensions
    {

        /// <summary>
        /// 取两个字符串中间的字符串
        /// </summary>
        /// <remarks>"aabbcc".Substring("aa","cc")返回bb</remarks>
        public static string Substring(this string str, string start, string end)
        {
            string _result = string.Empty;
            int _iStart = str.IndexOf(start);
            int _iEnd = str.IndexOf(end);
            if (_iStart != -1 && _iEnd > _iStart)
            {
                _result = str.Substring(_iStart + start.Length, _iEnd - _iStart - start.Length);
            }
            return _result;
        }

        /// <summary>
        /// 正则查找字符串
        /// </summary>
        /// <remarks>"aabbcc".Substring("b{2}","cc")返回bb</remarks>
        public static string Substring(this string str, string pattern)
        {
            return Regex.Match(str, pattern, RegexOptions.IgnoreCase).Value;
        }

        /// <summary>
        /// 正则查找字符串,返回指定的子字符串
        /// </summary>
        /// <remarks>"aabbcc".Substring("aa(bb)cc",1)返回bb</remarks>
        public static string Substring(this string str, string pattern, int num)
        {
            string _result = string.Empty;
            MatchCollection matches = Regex.Matches(str, pattern, RegexOptions.IgnoreCase);
            if (matches.Count > 0)
            {
                if(num >=0 && num <matches[0].Groups.Count)
                {
                    _result = matches[0].Groups[num].Value;
                }                
            }
            return _result;
        }

        /// <summary>
        /// 字符串拆分为字符串数组
        /// </summary>
        public static string[] Split(this string str, string separator)
        {
            return str.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries);
        }

        /// <summary>
        /// 字符串正则替换
        /// </summary>
        public static string Replace(this string str, string pattern, string replacement, bool isRegex)
        {
            return isRegex ? Regex.Replace(str, pattern, replacement) : str.Replace(pattern, replacement);            
        }
    }
}


评论: 0 | 引用: 0 | 查看次数: 1564
发表评论
登录后再发表评论!