Introduction
Eval3 library writen by Pascal Ganaye allows to parse and evaluate VB code, which is great but often it is not enough. What I needed was a class that would interpret a string
that contains multiple expressions enclosed in square brackets.
For example, this string:
GIS_[Format(Now, 'yy-MM-dd')]-[Field('ID')]-[Field('Source')]
will be evaluated to something like this:
GIS_10-01-13-5324523-DFS235F
Background
Let's assume we have an expression similar to the shown example above which we need to evaluate multiple times. I have writen a class that will parse the whole expression once and store "formulas" for future evaluations.
This significantly reduces execution time while keeping it really simple.
Using the Code
Download code: Eval3 Wrapper; Evaluation functions
It is very easy to use EvalFormulaCollection
class once you have Eval3
added to your project. You just need to:
- Create new instance of
EvalFormulaCollection
class with expression that you need to evaluate - Add "environment" object that provides functions that can be used in expression
- Call
Initiate()
method that will make reusable array of parsed "formulas" - Call
Value()
property to get the interpreted value of the expression which is evaluated without parsing!
Code example:
Sub Test()
Dim c As New MyClass
dim e as New evaluationFunctions
Dim expression As String = _
"GIS_[Format(Now, 'yy-MM-dd')]-[Field('ID')]-[Field('Source')]"
Dim ev as New EvalFormulaCollection(expression)
ev.AddEnvironment(c)
ev.AddEnvironment(e)
ev.Initiate()
MsgBox ev.Value()
End Sub
Points of Interest
The best thing about this code is its size. It is quite impressive what you can do with Regex
class from RegularExpressions
library with one line of code:
Public Sub New(ByVal expression As String)
...
_matches = Regex.Matches(_expression, "[\[][^\[\]]{1,}[\]]")
End Sub
CodeProject