How can I extract the value 2 from a string pid = {id=2}.
My code looks like
string pidnew= pid.Substring(3,5)
It's showing me error, have I made anything wrong?
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"
if there's only one number you can just Regex it
string pidnew = Regex.Match(pid, @"\d+").Value;
and you won't need to worry about the location
if you want to match on stateid:
string pidnew = Regex.Match(pid, @"(?<=stateid=)\d+",RegexOptions.IgnoreCase).Value;
The second parameter for Substring tells the number of characters to take. Thus if you have the string "{id=2}" and perform string pidnew= pid.Substring(3,5), what you're saying is: "Start at the character index 3 in the string (fourth character), and take five characters". This means the string would need to be at least 8 characters long. Since you only want to take one character, change the second parameter to a 1. You should also start at index 4 rather than 3 if the brackets are part of your string.
What you actually need is: string pidnew= pid.Substring(4,1);
Parameters
startIndex Type: System.Int32 The zero-based starting character position of a substring in this instance.
length Type: System.Int32 The number of characters in the substring.