I am trying to extract the values AGST, 1, or 2 from:
string order = "Tumbler (ID: AGST, Quantity: 1, Points each: 2)";
I have found a close answer on stack overflow here.
I would like to use a method similar to the top solution at the above link, but I think I have to change the regular expression in the line:
var pattern = string.Format("(?<=[\\{{\\s,]{0}\\s*=\\s*)\\d+", escIdPart);
Any help is greatly appreciated!
Edit:
Thanks for the help! Here is my current code -
protected void Page_Load(object sender, EventArgs e)
{
var order = "Tumbler (ID: AGST, Quantity: 1, Points each: 2)";
var id = GetValue("ID:", order); // should return "AGST"
var quantity = GetValue("Quantity:", order); // should return "1"
Label3.Text = id.ToString();
Label4.Text = quantity.ToString();
}
public string GetValue(string idPart, string test)
{
var escIdPart = Regex.Escape(idPart);
var pattern = string.Format(@": (.+)?,.*: (\d+).*(\d+)", escIdPart);
var result = default(string);
var match = Regex.Match(test, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
result = match.Value;
}
return result;
}
id.ToString() and quantity.ToString() both produce ": AGST, Quantity: 1, Points each: 2" when they should produce "AGST" and "1" respectively.
Again, any help is appreciated!
Edit 2: Solved!
Thanks for all the help! Here is my final code:
protected void Page_Load(object sender, EventArgs e)
{
var order = "Tumbler (ID: AGST, Quantity: 1, Points each: 2)";
var id = GetValue(1, order); // returns "AGST"
var quantity = GetValue(2, order); // returns "1"
var cost = GetValue(3, order); // returns "2"
Label3.Text = id.ToString();
Label4.Text = quantity.ToString();
Label5.Text = cost.ToString();
}
public string GetValue(int group, string test)
{
var pattern = @": (.+)?,.*: (\d+).*(\d+)";
var result = default(string);
var match = Regex.Match(test, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
result = match.Groups[group].Value;
}
return result;
}
Edit 3: "var pattern" expression change
I found that the expression only works if the value after "Points each: " is one digit. I changed the expression and now it seems to work fine with any number of digits in the values following "Quantity: " and "Points each: " - any objections/suggestions? Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
var order = "Tumbler (ID: AGST, Quantity: 1, Points each: 2)";
var id = GetValue(1, order); // returns "AGST"
var quantity = GetValue(2, order); // returns "1"
var cost = GetValue(3, order); // returns "2"
Label3.Text = id.ToString();
Label4.Text = quantity.ToString();
Label5.Text = cost.ToString();
}
public string GetValue(int group, string test)
{
var pattern = @": (.+)?,.*: (\d+).*: (\d+)";
var result = default(string);
var match = Regex.Match(test, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
result = match.Groups[group].Value;
}
return result;
}

[\\{{\\s,]{0}mean?