在C#中使用字符串函数给ArgumentOutOfRangeException异常 [英] Using substring function in C# gives ArgumentOutOfRangeException exception
本文介绍了在C#中使用字符串函数给ArgumentOutOfRangeException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能从字符串中提取值2 PID = {ID = 2}
。
我的code看起来像
string pidnew= pid.Substring(3,5)
它显示了我的错误,因为我已什么错?
It's showing me error, have I made anything wrong?
推荐答案
要获得个人价值,如同字符串PID字符串={ID = 2,genderid = 5,STATEID = 4}
,您可以使用此方法:
To get individual values out of a string like string pid = "{id=2, genderid=5, stateid=4}"
, you could use this method:
public string GetValue(string idPart, string test)
{
var escIdPart = Regex.Escape(idPart);
var pattern = string.Format("(?<=[\\{{\\s,]{0}\\s*=\\s*)\\d+", escIdPart);
var result = default(string);
var match = Regex.Match(test, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
result = match.Value;
}
return result;
}
...
var pid = "{id=2, genderid=5, stateid=4}";
var id = GetValue("id", pid); // returns "2"
var genderid = GetValue("genderid", pid); // returns "5"
var stateid = GetValue("stateid", pid); // returns "4"
这篇关于在C#中使用字符串函数给ArgumentOutOfRangeException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文