begin process at 2010 02 10 12:18:00
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

.NET

 > UN MINI LEXER À PARTIR DE VOTRE ENUMÉRATION

UN MINI LEXER À PARTIR DE VOTRE ENUMÉRATION


 Information sur la source

Note :
7 / 10 - par 1 personne
7,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :.NET Source .NET ( DotNet ) Classé sous :lexer, enumération Niveau :Initié Date de création :23/03/2004 Vu :5 945

Auteur : geniusishere

Ecrire un message privé
Commentaire sur cette source (0)
Ajouter un commentaire et/ou une note

 Description

cette classe "parse" votre texte pour le rendre sous forme de "TOKEN".
les TOKENs sont représentés par une enumération. à chaque TOKEN est associé un motif, ainsi lorsque qu'un motif est trouvé dans le texte son token est retourné.

Source

  • #region Imports
  • using System;
  • using System.Collections;
  • using System.Text.RegularExpressions;
  • #endregion
  • namespace Lexer
  • {
  • /// <summary>
  • /// mini lexer basé sur Regex
  • /// </summary>
  • public class MiniLexer
  • {
  • #region Variables
  • private int FCurPos;
  • private Object FCurToken;
  • private string[] FPatterns;
  • private Regex[] FRegExs;
  • private string FText;
  • private string FTokenString;
  • private Type FType;
  • private ArrayList FValues;
  • #endregion
  • /// <summary>
  • /// constructeur
  • /// </summary>
  • /// <param name="enumType">le type enum utiliser pour les tokens</param>
  • /// <param name="patterns">la liste des partterns, un par enum</param>
  • public MiniLexer(Type enumType, params string[] patterns)
  • {
  • if (enumType == null)
  • throw new ArgumentNullException("enumType", "ce paramètre doit être != null");
  • if (patterns == null)
  • throw new ArgumentNullException("patterns", "ce paramètre doit être != null");
  • if (!enumType.IsEnum)
  • throw new ArgumentException("cet argument doit être un enum", "enumType");
  • if (Enum.GetNames(enumType).Length != patterns.Length)
  • throw new Exception("enumType.Length != patterns.Length !");
  • FType = enumType;
  • FPatterns = patterns;
  • FValues = new ArrayList(Enum.GetValues(FType));
  • int i = 0;
  • //init des patterns
  • FRegExs = new Regex[FPatterns.Length];
  • foreach(string s in FPatterns)
  • {
  • FRegExs[i] = new Regex(s);
  • i++;
  • }
  • }
  • /// <summary>
  • /// provoque la lecture du prochain token
  • /// </summary>
  • /// <returns>retourne la valeur d'un token, null si aucun token ne correspond au texte</returns>
  • public Object NextToken()
  • {
  • int i;
  • int maxlen, index;
  • index = -1;
  • maxlen = -1;
  • for(i = 0; i < FRegExs.Length; i++)
  • {
  • Regex r = FRegExs[i];
  • Match m = r.Match(FText, FCurPos);
  • //recherche du match le plus grand à la position FCurPos
  • if (m.Success && m.Index == FCurPos && m.Length > maxlen)
  • {
  • index = i;
  • maxlen = m.Length;
  • }
  • }
  • if (index != -1)
  • {
  • FTokenString = FText.Substring(FCurPos, maxlen);
  • FCurPos += maxlen;
  • FCurToken = FValues[index];
  • }
  • else
  • FCurToken = null;
  • return FCurToken;
  • }
  • /// <summary>
  • /// retourne la chaîne correspondant au token courant
  • /// </summary>
  • public string TokenString
  • {
  • get
  • {
  • return FTokenString;
  • }
  • }
  • /// <summary>
  • /// retourne le token courant
  • /// </summary>
  • public Object Token
  • {
  • get
  • {
  • return FCurToken;
  • }
  • }
  • /// <summary>
  • /// indique si on est à la fin du texte
  • /// </summary>
  • public bool Eof
  • {
  • get
  • {
  • return FCurPos >= FText.Length;
  • }
  • }
  • /// <summary>
  • /// le Texte à "lexer"
  • /// </summary>
  • public string Text
  • {
  • get
  • {
  • return FText;
  • }
  • set
  • {
  • FText = value;
  • FCurPos = 0;
  • FTokenString = string.Empty;
  • }
  • }
  • }
  • }
#region Imports
using System;
using System.Collections;
using System.Text.RegularExpressions;
#endregion

namespace Lexer
{
	/// <summary>
	/// mini lexer basé sur Regex
	/// </summary>
	public class MiniLexer
	{
		#region Variables
		private int				FCurPos;
		private Object		FCurToken;
		private string[]	FPatterns;
		private Regex[]		FRegExs;
		private string		FText;
		private string		FTokenString;
		private Type			FType;
		private ArrayList	FValues;
		#endregion

		/// <summary>
		/// constructeur 
		/// </summary>
		/// <param name="enumType">le type enum utiliser pour les tokens</param>
		/// <param name="patterns">la liste des partterns, un par enum</param>
		public MiniLexer(Type enumType, params string[] patterns)
		{
			if (enumType == null)
				throw new ArgumentNullException("enumType", "ce paramètre doit être != null");
			if (patterns == null)
				throw new ArgumentNullException("patterns", "ce paramètre doit être != null");
			if (!enumType.IsEnum)
				throw new ArgumentException("cet argument doit être un enum", "enumType");
		
			if (Enum.GetNames(enumType).Length != patterns.Length)
				throw new Exception("enumType.Length != patterns.Length !");

			FType = enumType;
			FPatterns = patterns;
			FValues = new ArrayList(Enum.GetValues(FType));
			int i = 0;
			//init des patterns
			FRegExs = new Regex[FPatterns.Length];
			foreach(string s in FPatterns)
			{
				FRegExs[i] = new Regex(s);
				i++;
			}
		}
		/// <summary>
		/// provoque la lecture du prochain token
		/// </summary>
		/// <returns>retourne la valeur d'un token, null si aucun token ne correspond au texte</returns>
		public Object NextToken()
		{
			int i;
			int maxlen, index;

			index = -1;
			maxlen = -1;
			for(i = 0; i < FRegExs.Length; i++)
			{
				Regex r = FRegExs[i];
				Match m = r.Match(FText, FCurPos);
				//recherche du match le plus grand à la position FCurPos
				if (m.Success && m.Index == FCurPos && m.Length > maxlen)
				{
					index = i;
					maxlen = m.Length;
				}
			}
			if (index != -1)
			{
				FTokenString = FText.Substring(FCurPos, maxlen);
				FCurPos += maxlen;
				FCurToken = FValues[index];
			}
			else
				FCurToken = null;
			return FCurToken;
		}

		/// <summary>
		/// retourne la chaîne correspondant au token courant
		/// </summary>
		public string TokenString
		{
			get
			{
				return FTokenString;
			}
		}

		/// <summary>
		/// retourne le token courant
		/// </summary>
		public Object Token
		{
			get
			{
				return FCurToken;
			}
		}
		
		/// <summary>
		/// indique si on est à la fin du texte
		/// </summary>
		public bool Eof
		{
			get
			{
				return FCurPos >= FText.Length;
			}
		}

		/// <summary>
		/// le Texte à "lexer"
		/// </summary>
		public string Text
		{
			get
			{
				return FText;
			}
			set
			{
				FText = value;
				FCurPos = 0;
				FTokenString = string.Empty;
			}
		}
	}
}

 Conclusion

voici une exemple d'utilisation

enum TokenRules {LBRACE, RBRACE, IDENT, STRING, OR, SPACE}
MiniLexer tkRules = new MiniLexer(typeof(TokenRules), "\\(", "\\)", "[A-Za-z]+[A-Za-z0-9_]*" , "'[^']*'", "\\|", " ");
tkRules.Text = "NUMBER '+' EXPRESSION";
while (!tkRules.Eof)
{
    Console.WriteLine(tkRules.NextToken().ToString());
}

un autre exemple

enum Test {NUMBER, SPACE, PLUS, MOINS};
tkRules = new MiniLexer(typeof(Test), "[0-9]+", " ", "\\+", "-");
tkRules.Text = "456 + 89 - 3";
while (!tkRules.Eof)
{
     Console.WriteLine(tkRules.NextToken().ToString());
}




 Sources du même auteur

Source avec Zip Source avec une capture Source .NET (Dotnet) UN AUTRE TREEVIEW
Source avec Zip Source avec une capture Source .NET (Dotnet) TABPAGE STYLE VS2005

 Sources de la même categorie

Source avec Zip CHAT SERVER-CLIENT par abderrahmenbilog
Source avec Zip Source avec une capture Source .NET (Dotnet) SIMULATION DE CONSOLE POUR WINDOWS MOBILE par originalcompo
Source avec Zip Source .NET (Dotnet) BASE DE DONNÉES EN XML par DanMor498
Source avec Zip Source avec une capture Source .NET (Dotnet) SIMPLECONV - APPLICATION DE CONVERSION MONÉTAIRE AVEC TAUX E... par Jeffrey_
Source avec Zip Source .NET (Dotnet) TRAITEUR D'IMAGE (MINI) par ycyril

Commentaires et avis

Aucun commentaire pour le moment.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Enumération et action sur une fenêtre windows [ par Laraldie ] Bonsoir, Mon problème est simple mais pas facile à expliquer. En interaction avec une autre application (un gestionnaire de base de données qui récup Enumération [ par thorgal1612 ] Bonjour,J'ai déjà poser cette question mais sans succès, je tente une nouvelle fois...Pour un report fait avec CrytalReport, la propriété "PaperSize" L'enumération en C# [ par LordOfTheShadow ] Hello, tout le monde!!! J'ai trop du mal avec les énumérations alors si quelqu'un peut m'aider...Tout d'abord je travaille sur un UserControl. Je voud


Nos sponsors


Sondage...

Comparez les prix


HTC Magic

Entre 429€ et 429€

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,562 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales