tags:

views:

95

answers:

4

Hello,

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

+5  A: 

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));
Talljoe
Remember, this won't work under .NET 2.0 or 3.0 due to requiring Linq!
MiffTheFox
Then don't use Linq. Linq isn't the important bit here.
Talljoe
Is the "<id>" part standard? I've never seen it.
mafutrct
That syntax ("<id>") allows you to name the group and exists in PCRE regex syntax. .NET Regex allows you to do "(?<groupName>.*)" or "(?'groupname'.*)". The latter is not compatible with other Regex libraries.
Talljoe
+2  A: 

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. ;-)

MiffTheFox
+1  A: 

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;
Josh Einstein
+2  A: 

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]);
  }
}
Jeff Meatball Yang