Reputation: 13
I have real time response from web service as follows :
ok,SIP/2417,15,default,N
I can save this in text file.
The only thing change is 2417 and 15.
Now I want to explode 2417 and 15 from text file and save in variable or database.
For Database I have Column Ext and Ringtime
Upvotes: 1
Views: 656
Reputation: 38880
This should work:
var test = "ok,SIP/2417,15,default,N";
var regex = new Regex("^ok,SIP/(?<number1>\\d+),(?<number2>\\d+),default,N$");
var match = regex.Match(test);
var val1 = match.Groups["number1"].Value;
var val2 = match.Groups["number2"].Value;
But this would also work:
var test = "ok,SIP/2417,15,default,N";
var values = test.Split(',');
var val1 = values[1].Substring(4);
var val2 = values[2];
Note that they will still be strings at this stage, so you'll need to parse them if you require them as integers:
var number1 = int.Parse(val1);
var number2 = int.Parse(val2);
** TryParse
is a better option if you go with the Split
option.
Upvotes: 1
Reputation: 1600
If you want to have a generic regex you can try is
Regex r = new Regex(@"([\d]+,[\d]+)");
string var = "ok,SIP/2417,15,default,N";
Match match = r.Match(var);
if you want list of those vars then below is the dynamic solution for any count of number.
List<int> vals = new List<int>();
vals.AddRange(match.Groups[0].Value.Split(',').Select(x => Convert.ToInt32(x)));
else if you're going to have fixed two values then.
int val = Convert.ToInt32(match.Groups[0].Value.Split(',')[0]);
int val2 = Convert.ToInt32(match.Groups[0].Value.Split(',')[1]);
Upvotes: 0