如何截取字符串字符

hawesome.xu 2013-01-09 09:09:18
有一个很长的字符串s,我要截取其中 usedID="xxx"(注:xxx可能为0-999之间的任何整数)里面usedID的值是多少.在字符串s中有多个的usedID="xxx"。
例子,"asdfd23fej +==fief1423difjj usedID="92"dfdifj"A"adfd fdfe usedID="123"dref".
就是我要取出其中的92和123.。。。
...全文
132 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
oreoconansisu 2013-01-09
  • 打赏
  • 举报
回复
private string _GetStr(string str,string matchStr,string quoteStr)
        {
            int index = str.IndexOf(matchStr);

            string value = "";
            
            while (index >= 0)
            {
                if (value != "")
                {
                    value += ",";
                }
                value += _MappingStr(ref str, matchStr, quoteStr,index);
                index = str.IndexOf(matchStr);
            }

            return value;
        }

        private string _MappingStr(ref string str, string matchStr, string quoteStr,int index)
        {
            int startIndex = -1;
            int endIndex = -1;

            startIndex = str.Substring(index, str.Length - index).IndexOf(quoteStr);
            if (startIndex > 0)
            {
                startIndex += index + 1;
            }

            endIndex = str.Substring(startIndex + 1, str.Length - startIndex - 1).IndexOf(quoteStr);
            if (endIndex > 0)
            {
                endIndex += startIndex;
            }

            if (startIndex >= 0 && endIndex >= 0)
            {
                string value = str.Substring(startIndex, endIndex - startIndex + 1);

                str = str.Substring(endIndex+1, str.Length - endIndex-1);

                return value;
            }
            else
            {
                return "";
            }
        }

//调用
string str = "asdfd23fej +==fief1423difjj usedID=\"92\"dfdifj\"A\"adfd fdfe usedID=\"123\"dref";
str = _GetStr(str, "usedID", "\"");
hawesome.xu 2013-01-09
  • 打赏
  • 举报
回复
好的,谢谢大家。可以了。
  • 打赏
  • 举报
回复
楼上的正则应该可行
  • 打赏
  • 举报
回复
晕,看错了,这个方法取出的是92"dfdifj"A"adfd 和123"dref。 等别的高手来看下吧
q107770540 2013-01-09
  • 打赏
  • 举报
回复
string str = "asdfd23fej +==fief1423difjj usedID=\"92\"dfdifj\"A\"adfd fdfe usedID=\"123\"dref";
             var ary = Regex.Matches(str, @"(?i)(?<=usedid=([""']?)\d+(?=\1)).OfType<Match>().Select(t => Convert.ToInt32(t.Value)).ToArray();
kunkun0921 2013-01-09
  • 打赏
  • 举报
回复
使用正则表达式提取
  • 打赏
  • 举报
回复
string str = "asdfd23fej +==fief1423difjj usedID=\"92\"dfdifj\"A\"adfd fdfe usedID=\"123\"dref"; var ary = Regex.Matches(str, @"(?is)(?<=(^|[^a-z])usedid=[""'])\d+").OfType<Match>().Select(t => Convert.ToInt32(t.Value)).ToArray();
  • 打赏
  • 举报
回复

string[] arr = s.Split(' ');
foreach(string str in arr)
{
  if(str.Length>7 && str.Substring(0,7).Equals("userId="))
{
   string userId = str.split('=').Trim('\"');
   //对取出的userId进行处理
}
}

110,502

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧