Come estraggo un valore dall'interno di una stringa formattata?
Domanda
Ho ottenuto un array di stringhe e i valori sono i seguenti
sNames[0] = "Root | [<root>] | [ID = 1]";
sNames[1] = "Planning | [Root] | [ID = 2]";
Da questo vorrei solo estrarre il valore ID .. 1,2 ..
per ora lo faccio come:
foreach (var s in sNames)
{
int id = Convert.ToInt32(s.Split('|')[2].Split('=')[1].Substring(1,1));
...
}
C'è qualche altro buon modo per farlo?
Grazie
Soluzione
Puoi usare una regex per trovare l'ID (la parte Match () potrebbe non essere corretta al 100% - esercizio lasciato al lettore).
var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]");
var ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value));
Altri suggerimenti
Puoi usare 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());
// ...
}
Ma ora hai due problemi . ; -)
Sembra un lavoro per le espressioni regolari. Questo abbinerà tutte le stringhe con il modello di " ID = [un certo numero] "
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]);
}
}
Le espressioni regolari sono le "quotazioni più semplici". Con l'avvertenza ovviamente che esiste un'enorme curva di apprendimento per regex.
Regex rx = new Regex(@"\[ID\s*=\s*(?<id>\d+)\]");
Match m = rx.Match(str);
string id = m.Groups["id"].Value;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow