I have been developing an application that one of it's responsability is provide to user an page that it's possible to write math expression in EXCEL WAY.
It is an application in ASP.NET MVC, and it's use the SpreadSheetGear library to EXECUTE excel expression.
As it's show below, The page has an texarea to write expression and two button on the right. The green one is for VALIDATE THE EXPRESSION and the red one is for clean textarea.
A,B,C are parameter, that application will replace for values. Notice that it is not possible to know the parameter data type. I mean, if I write a concatenate function, It is necessary that user use double quotes (") to delimitate string. For example
CONCATENATE("A","B") thus, is necessary that user KNOW functions parameters and its correlate data types.
My main issue is how to validate the expression?
SpreadSheetGear there isn't any method to perform this validation.
The method spreadsheetgear provides to perform an formula is:
string formula = "{formula from textarea}"
worksheet.EvaluateValue(formula)
and it's expect and string.
As I don't know what formula user will write, or how many parameters this formula has and what are the parameters data type, it's kind difficult to validate.
Now my question is?
How could I validate the expression?
I think in an alternative: Provide to user and page with textbox for each parameter in the expression. The user will be able to provide some data and validate the RESULT of formula. If the sintaxe of formula is wrong the application throw an exception.
It would be a good solution, but for each "PROCESS" that user will interact to, He'll write 10, 15 formulas, and maybe it would be little painful.
Anyone could provide me an Good solution for that?
Thank you!
https://sites.google.com/site/akshatsharma80/home/data-structures/validate-an-arithmetic-expression
refer this site for validation
This is a very late response but I have been working on expression evaluators in Excel with VBA for a while and I might shed some light. I have three solutions to try but all have limitations.
1) Ask the user to put a '$' after a variable name to signify a string (or some other unique character). Drawback is that it is not as simple as typing a single letter for a variable.
2) Assume all variables entered are double precision. Then change the variable to strings in all combinations until one combination works. Could be very time consuming to try all the combinations if the user enters lots of individual variables.
3) Assume all variables entered are double precision. But then have a list in your program of functions that require strings for parameters. Then you could parse the expression, lookup the functions in your list and then designate the parameters that require string input with a string signifier (like in step 1). This will not account for user defined functions.
Now to test out the function, replace all the numeric variables with '1' and all the string variables with "a", then EvaluateValue. If you get a result or an error signifying a calculation error, it is good.
BTW, in order to parse the expression, I suggest the following method. I do not know C#, only VB, so I will only talk in general terms.
1) Take your expression string and do a search and replace of all the typical operators with the same operator but with a backslash ("\") in front and behind the operator (you can use any other character that is not normally used in Excel formulas if you like). This will delineate these operators so that you can easily ignore them and split up your expression into chunks. Typically only need to delineate +,-,/,*,^,<,>,= and {comma}. So search for a "+" and replace it with a "\+\" and so on. For parenthesis, replace "(" and ")" with "(\\" and "\\)" respectively.
So your sample formula "SUM(A, SQRT(B, C)) * PI()" will look like this:
"SUM(\\A\,\ SQRT(\\B\,\ C\\)\\) \*\ PI(\\\\)"
You can also clean up the string a bit more by eliminating any spaces and by eliminating redundant backslashes by replacing every three consecutive backslashes with a single one (replace "\\" with "\").
2) In Visual Basic there is a command called 'Split' that can take a string like this and split it into a one dimensional array using a delimiter (in this case, the backslash). There must be an equivalent in C# or you can just make one. Your array will look like this: "SUM(", "", "A", ",", "SQRT(", "", "B", etc.
Now iterate through your array, starting at the first element and then skipping every other element. These elements will either be a number (a numeric test), a variable, a function (with have a "(" at the end of it), a parenthesis or blank.
Now you can do other checks as you need and replace the variables with actual values.
3) When you are done, rejoin the array back into a string, without any delimiters, and try the Evaluate function.
Related
So what I'm trying to do is that I want my bot to be able to have two different parameters. Like what I mean is something like I can extract like a certain part of it and then after there's a "," or another symbol I can extract the following separately. So I get two different strings from one input. So like I have two strings and I want one of them to be the first half and the second one to be the rest. And I am not planning on updating to 1.0 so tell me if it's not possible in 0.9.6.
Your question isn't very clear but I think I know what you are looking for. This is a general answer for C# as I don't know how the Discord interface differs. You seem to be taking input in the form of a string, for example: play *songname*,*channelname*. To split this string into two inputs you want to use String.Split(',')
An example would be this:
string stringTakenFromDiscord = "play *songname*,*channelname*";
String[] input = stringTakenFromDiscord.Split(',');
//input[0] will be equal to what comes before the comma
//if you were to print it, it would be "play *songname*"
//input[1] will be what comes after the comma
//if you were to print it, it would be "*channelname*"
Now you can do anything you want with either of the values of the array input[] and feed them through your code to parse them. Do note that when it splits by the character, the character won't appear in either of the output strings. This will only work for inputs that only have one instance of your chosen character. You can change the character to whatever you want.
It occurs to me that it might be easier to just take the input on two separate lines instead.
In our C# desktop-application we generate a lot of dynamic sql-queries. Now we have some troubles with single quotes in strings. Here's a sample:
INSERT INTO Addresses (CompanyName) VALUES ('Thomas' Imbiss')
My question is: How can I find and replace all single quotes between 2 other single quotes in a string? Unfortunately I can't replace the single quotes when creating the different queries. I can only do that after the full query is created and right before the query gets executed.
I tried this pattern (Regular Expressions): "\w\'\w"
But this pattern doesn't work, because after "s'" there's a space instead of a char.
I am sorry to say, there is no solution in approach you expect.
For example, have these columns and values:
column A, value ,A',
column B, value ,B',
If they are together in column list, you have ',A',',',B','.
Now, where is the boundary between first and second value? It is ambiguous.
You must take action when creating text fields for SQL. Either use SQL parameters or properly escape qoutes and other problematic characters there.
Consider showing the above ambiguous example to managers, pushing the whole problem back as algorithmically unsolvable at your end. Or offer implementing a guess-work and ask them whether they will be happy if content of several text fields can get mixed in some cases like above one.
At time of SQL query creation, if they do not want to start using SQL parameters, the solution for enquoting any input string is as simple as replacing:
string Enquote(string input)
{
return input.All(c => Strings.AscW(c) < 128) ? "'" : "N'"
+ input.Replace("'", "''")
+ "'"
}
Of course, it can have problem with deliberately malformed Unicode strings (surrogate pairs to hide ') but it is not normally possible to produce these strings through the user interface. Generally this can be still faster than converting all queries to versions with SQL parameters.
I will try to describe my problem as well as I can.
I am trying to write a program that will handle equations like:
F = (X∨A) ↔ (X∨B) ( (X OR A) is equivalent to (X OR B) )!
I have to solve it by 'X', or to better say, write disjunctive and/or conjunctive normal form.
So, theoretically, it goes like this:
When the truth table is written, you have to see when F is equal to 1 (tautology), and write conjunctive/disjunctive normal form.
For example (disjunctive normal form for the given table):
For A=0,B=0 and A=1,B=1, the value of X does not matter, and for A=0,B=1 AND A=1,B=0, X must be 1.
In the end,
X=A∨B.
Since I'm writing it in C#, equations are written in a TextBox.
What bothers me,is how should I separate my string so I can solve it part by part?
What about first trying "Split()" method (or other methods) of the class String in C#? In the first place, you'd better push your users to insert a blank (as the separator of Split()) between each pair of tokens (e.g. A AND B) , so that you can concentrate on the main logic of your solver.
I see. It's basically a simplifying calculator that doesn't (necessarily) have sequential input via buttons but a ready-made formula typed or pasted in a textbox.
What you need to do is therefore
define a set of permitted operators (AND, OR, NOT, XOR, etc.) in
various permitted notations (Λ, V, !, =, !=, etc., +,*,-,=, ↔ etc.)
check whether the input is syntactically correct; which means
you'll probably have to first remove all spaces from the input
string, then use regular expressions for allowed constructs, which
will probably prove to be a pain
if input is valid, check for parentheses first to determine grouped
expressions
simplify according to boolean algebra
Or simply follow this link (Java but still): Boolean expression solver/simplifier, use the tool bc2cnf or any other library that is linked there and spare yourself a lot of headache by restricting the permitted input to one permitted by the used library.
Hope this helps.
Is it possible to generate regular expressions from a user entered string? Are there any C# libraries to do this?
For example a user enters a string e.g. ABCxyz123 and the C# code automatically generates [A-Z]{3}[a-z]{3}\d{3}.
This is a simple string but we could have more complicated strings like
MON-0123/AB/5678-abc 2/7
Or
1234-678/abc::1234ABC?246
I already have a string tokeniser (from a previous stackoverflow question) so I could construct a regex from the list of tokens.
But I was wondering if there is a lib or C# code out there that’ll do it.
Edit: Important, I should of also said: It's not the actual character in the string that are important but the type of character and how many.
e.g A user could enter a "pattern" string of ABCxyz123.
This would be interpreted as
3 upper case alphas followed by
3 lower case alphas followed by
3 digits
So other users (when complied) must enter strings that match that pattern [A-Z]{3}[a-z]{3}\d{3}., e.g. QAZplm789
It's the format of user entered strings that's need to be checked not the actual content if that makes sense
Jerry has a related link
creating a regular expression for a list of strings
There are a few other links off this.
I'm not trying to do anything complicated e.g NLP etc.
I could use C# expression builder and dynamic linq at a push, but that seems overkill and a code maintainable nightmare .
I'll write my own "simple" regex builder from the tokenized string.
Example Use Case:
An admin office user where I work could setup the string patterns for each field by typing a string pattern, My code converts this to a regex, I store these in a database.
E.g: Field one requires 3 digits at the start. If there are 2 digits then send to workflow 1 if 3 then send to workflow 2. I could simply check the number of chars by substr or what ever. But this would be a concrete solution.
I am trying to do this generically for multiple documents with multiple fields. Also, each field could have multiple format checkers.
I don't want to write specific C# checks for every single field in numerous documents.
I'll get on with it, should keep me amused for a couple of days.
My question may sound weird but that's the scenario i'm at.
I need to parse an Excel formula (getting it from Office.Interop.Excel) and get the parameters from the formula (# of parameter can vary)
There are multiple cases to consider.
E.g.:
1. myformula("param1", "param2")
2. myformula("param1", A2)
3. myformula("param1", , "param3")
4. myformula(A1, , "param3")
5. myformula("param1, has commas in it", "param2")
Is there a nicer way to parse this as opposed to having multiple if branches (especially considering when string array is mixed, i.e. some parameters have quotations and other parameters are reference parameters)?
Using string split(',') doesn't seem to be too helpful as I can have commas in the parameter itself.
I've also tried
string[] paramArray = new string[]{(parameters)}
where parameters = "\"param1\", \"param2\"";
but that didn't seem to work either (it won't work at all if I have an empty parameter but that's another case).
My outcome should be some sort of an array (or list or any other collection) that would contain all of the parameters, and if a parameter didn't have quotation marks in it then I would need to evaluate it.
Any help would be appreciated.
I would process the string looking for " or , if " found search fwd looking for the closing " ignoring any , along the way and taking into account the possibility of impeded "'s in the parameter. When you get the closing " resume looking for " or , and repeat.
Another option would be to use split but then check the results for elements beginning with " . Merge these with the next array element to for the complete parameter (may be that > 2 consecutive array element need to be merged) Also watch out for strings like "zzz"",""xxx" (a single string that = zzz","xxx)