Il semble que la plupart des messages ici décrivent ce dont vous avez besoin. Cependant, vous pourriez avoir besoin d'un comportement plus complexe, en fonction de ce que vous analysez. Dans votre cas, il se peut que vous n'ayez pas besoin d'une analyse syntaxique plus complexe, mais cela dépend des informations que vous extrayez.
Vous pouvez utiliser des groupes regex comme nom de champ dans la classe, après quoi on pourrait écrire par exemple comme ceci :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
public class Info
{
public String Identifier;
public char nextChar;
};
class testRegex {
const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. " +
"Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";
static void Main(string[] args)
{
Regex regex = new Regex(@"%download%#(?<Identifier>[0-9]*)(?<nextChar>.)(?<thisCharIsNotNeeded>.)");
List<Info> infos = new List<Info>();
foreach (Match match in regex.Matches(input))
{
Info info = new Info();
for( int i = 1; i < regex.GetGroupNames().Length; i++ )
{
String groupName = regex.GetGroupNames()[i];
FieldInfo fi = info.GetType().GetField(regex.GetGroupNames()[i]);
if( fi != null ) // Field is non-public or does not exists.
fi.SetValue( info, Convert.ChangeType( match.Groups[groupName].Value, fi.FieldType));
}
infos.Add(info);
}
foreach ( var info in infos )
{
Console.WriteLine(info.Identifier + " followed by '" + info.nextChar.ToString() + "'");
}
}
};
Ce mécanisme utilise la réflexion C# pour définir la valeur de la classe. Le nom du groupe est comparé au nom du champ dans l'instance de la classe. Veuillez noter que Convert.ChangeType n'accepte aucun type de déchets.
Si vous voulez ajouter le suivi de la ligne / colonne - vous pouvez ajouter une division Regex supplémentaire pour les lignes, mais afin de garder la boucle for intacte - tous les modèles de correspondance doivent avoir des groupes nommés. (Sinon, l'index de la colonne sera calculé de manière incorrecte).
Le résultat sera le suivant :
456 followed by ' '
3434 followed by ' '
298 followed by '.'
893434 followed by ' '