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..
从这个我想提取ID值.. 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
4 个解决方案
#1
You can use a regex to find the ID (the Match() part may not be 100% correct -- exercise left to the reader).
您可以使用正则表达式来查找ID(匹配()部分可能不是100%正确 - 练习留给读者)。
var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]");
var ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value));
#2
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. ;-)
但现在你有两个问题。 ;-)
#3
Sounds like a job for regular expressions. This will match all strings with the pattern of "ID = [some number]"
听起来像正则表达式的工作。这将匹配所有字符串的模式为“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]);
}
}
#4
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;
#1
You can use a regex to find the ID (the Match() part may not be 100% correct -- exercise left to the reader).
您可以使用正则表达式来查找ID(匹配()部分可能不是100%正确 - 练习留给读者)。
var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]");
var ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value));
#2
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. ;-)
但现在你有两个问题。 ;-)
#3
Sounds like a job for regular expressions. This will match all strings with the pattern of "ID = [some number]"
听起来像正则表达式的工作。这将匹配所有字符串的模式为“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]);
}
}
#4
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;