Reputation: 30045
I got a string array and values are as follows
sNames[0] = "Root | [<root>] | [ID = 1]";
sNames[1] = "Planning | [Root] | [ID = 2]";
From this I would like to just extract ID value .. 1,2..
for now am do this as :
foreach (var s in sNames)
{
int id = Convert.ToInt32(s.Split('|')[2].Split('=')[1].Substring(1,1));
...
}
Is there some other good way to do it ?
Thanks
Upvotes: 1
Views: 195
Reputation: 39057
Sounds like a job for regular expressions. This will match all strings with the pattern of "ID = [some number]"
using System.Text.RegularExpressions;
...
foreach(string s in sNames) {
Match m = Regex.Match("ID = ([0-9]+)");
if(m.Success) {
int id = Convert.ToInt32(m.Groups[1]);
}
}
Upvotes: 2
Reputation: 14827
You can use a regex to find the ID (the Match() part may not be 100% correct -- exercise left to the reader).
var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]");
var ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value));
Upvotes: 5
Reputation: 69282
Regular expressions is the "easiest". With the caveat of course that there's a huge learning curve for regex.
Regex rx = new Regex(@"\[ID\s*=\s*(?<id>\d+)\]");
Match m = rx.Match(str);
string id = m.Groups["id"].Value;
Upvotes: 1
Reputation: 21575
You can use regex...
// using System.Text.RegularExpressions
Regex rx = new Regex(@"\[ID\s*=\s*(\d+)\]", RegexOptions.IgnoreCase);
foreach (var s in sNames)
{
Match m = rx.Match(s);
if (!m.Success) continue; // Couldn't find ID.
int id = Convert.ToInt32(m.Groups[1].ToString());
// ...
}
But now you have two problems. ;-)
Upvotes: 2