I'm currently looking at building a calculation parser tool for a Rules Engine project.
The calculation takes the form of a string which I was using string.split(' ') to get into an array of values, separating the values and operators:
expression = "5 + 6 - 8"
expression.split(' ');
[0]:5
[1]:+
[2]:6
[3]:-
[4]:8
My code uses this array to get the answer 3 - at the moment I'm just doing left to right evaluation and dealing with operator precedence.
I'm looking to extend the calculation string to work with dates - adding or subtracting minutes from a date time, unfortunately my DateTime has a space so I get the result:
expression = "12/12/2016 12:00:00 + 30 - 10"
expression.split(' ');
[0]:12/12/2016
[1]:12:00:00
[2]:+
[3]:30
[4]:-
[5]:10
When I really want:
[0]:12/12/2016 12:00:00
[1]:+
[2]:30
[3]:-
[4]:10
I was hoping to solve this through a regular expression so I could also validate the string at the same time but unfortunately my knowledge of creating them is limited.
Would anyone have an example of a regular expression, or any suggestions on how I could potentially do this - getting the numbers and operators to be stored separately in an array? or is this not possible with regular expressions? would I be better off using String.Substring() instead to pull out the data?
edit
sln solution solved my issue, my final code looked like this:
var splitExp = Regex.Split(expression, @"[ ](?:(?=\D)|(?<=\D[ ]))");
Which gives:
expression = "12/12/2016 12:00:00"
splitExp[0] = "12/12/2016 12:00:00"
expression = "12/12/2016 12:00:00 + 30 - 10"
splitExp[0] = "12/12/2016 12:00:00"
splitExp[0] = "+"
splitExp[0] = "30"
splitExp[0] = "-"
splitExp[0] = "10"
Which is exactly what I was looking for.