C# 获取JSON字符串中匹配起始标识的字符串


DEMO:

       ///
        /// 获取字符串中多个匹配起止标志的字符串
        ///

        ///
        ///
        ///
        ///
        public static List GetMatchesWithoutStartEndFromString(string inputString, string patternStart, string patternEnd)
        {
            if (string.IsNullOrWhiteSpace(inputString))
                return null;             //定义正则表达式,解析得到  [ 与 ] 之间的内容,内容包括 [ 和 ]
            string patttern = string.Format(@"({0}).*?({1})", patternStart, patternEnd);             //解析得到多个 [ 与 ] 之间内容,保存在 matches 中
            List listItems = new List();
            MatchCollection matches = Regex.Matches(inputString, patttern, RegexOptions.IgnoreCase);
            foreach (Match m in matches)
            {
                listItems.Add(m.Value.Replace(patternStart, "").Replace(patternEnd, ""));
            }             return listItems;
        }         ///
        /// 获取字符串中单个匹配起止标志的字符串
        ///

        ///
        ///
        ///
        ///
        public static string GetMatchWithoutStartEndFromString(string inputString, string patternStart, string patternEnd)
        {
            if (!string.IsNullOrWhiteSpace(inputString))
            {
                string patttern = string.Format(@"({0}).*?({1})", patternStart, patternEnd);
                Match match = Regex.Match(inputString, patttern, RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    return match.Value.Replace(patternStart, "").Replace(patternEnd, "");
                }
            }             return string.Empty;
        }     使用:    string strUserName = StringHelper.GetMatchWithoutStartEndFromString(inputString, "\"UserName\":", ",");
            var regex = new System.Text.RegularExpressions.Regex(@"^\d+$");
            bool isMatch = regex.IsMatch(strUserName.Replace("\"", "").Replace("'", ""));
            if (!isMatch)
            { }