[英]How do I extract a value from inside of a formatted string?
我有一個字符串數組,值如下
sNames[0] = "Root | [<root>] | [ID = 1]";
sNames[1] = "Planning | [Root] | [ID = 2]";
從這里我只想提取ID值.. 1,2 ..
現在我這樣做是:
foreach (var s in sNames)
{
int id = Convert.ToInt32(s.Split('|')[2].Split('=')[1].Substring(1,1));
...
}
還有其他好的方法嗎?
謝謝
您可以使用正則表達式查找ID(Match()部分可能不是100%正確-留給讀者練習)。
var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]");
var ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value));
您可以使用正則表達式...
// 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());
// ...
}
但是現在你有兩個問題 。 ;-)
聽起來像是正則表達式的工作。 這將以“ 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]);
}
}
正則表達式是“最簡單的”。 需要注意的是,正則表達式的學習曲線很大。
Regex rx = new Regex(@"\[ID\s*=\s*(?<id>\d+)\]");
Match m = rx.Match(str);
string id = m.Groups["id"].Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.