Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Is it possible to convert a string expression into a boolean condition?
For example, I get the following string:
var b = "32 < 45 && 32 > 20"
I would like to create a bool expression out of this and invoke it. The string representation is also flexible (to make it more fun), so it allows ||, &&, ().
Have a look at Flee (Fast Lightweight Expression Evaluator) on CodePlex.
I would use Irony, the .NET language kit. You could construct a simple grammar with Irony and then parse the string into executable command. There's a decent example of an arthmetic grammar in this tutorial and in the Expression Grammar Sample, its a pretty common request ;)
I definitely suggest using a proper compiler as opposed to Regex or a roll your own approach - it will be much more extensible if you ever want to add more rules.
If it follows all C# expression rules then compile it as dynamic code as per http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm
If you're dealing with relatively simple mathematical expressions then a straightforward implementation of the shunting-yard algorithm should do the trick.
Take a look at my library, Proviant. It's a .NET Standard library using the Shunting Yard algorithm to evaluate boolean expressions. You could also implement your own grammar.
I think creating an interpreter for this string would not take too long time.
http://www.industriallogic.com/xp/refactoring/implicitLanguageWithInterpreter.html
here you can find information about design that can be used to create it.
You could take a look at JINT (Javascript Interpreter for .NET) http://jint.codeplex.com/
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to work on a C# project and I would like to allow the user to run code on the fly, by typing code into an editor.
So with that in mind, I thought about writing some sort of scripting editor, parser and evaluator, but wanted to check with other people first, in case I am just reinventing the wheel?
So, my idea is/was to...
Write a syntax highlighted editor that I can write code into,
including the use of custom keywords.
Add logic to the editor so that it will be able to format the
content based on the text in the editor.
Have a way of 'actioning' the text that has been entered.
For instance, if I enter the following...
if (Shape.IsACube())
{
// Do some cube stuff
}
else if (Shape.Area(height, length, width) > 40)
{
// Do some large area stuff
}
...then I would like to be able to run that code on the fly as though it was part of the application.
I hope all of that makes sense. Any thoughts?
Which grammar for your syntax you want to use? Your own or C# ?
If you just want to compile some C# code in runtime - you can use something like CodeDOM. Highlighting can be achieved through C# Syntax Highlighter.
If you want your own grammar with your terminals/non-terminals - you should use grammar makers like ANTLR4. This way you will understand how most compilers/interpretators works.
The main idea is that you write Lexer (which responsible for tokenization of your input) and Parser (which is actualy just list of grammar rules, 'productions' in other words). It will give you full AST from which you can evaluate/highlight your text. Many language grammars already written before you in here including C# syntax (even ANTLR4 itself is presented). So you can just pick some and modify it for your needs.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I plan to write a program or rather function which will be able to analyze a string parameter which in turn will be math expression. Only the 4 basic operations are allowed(addition, subtraction, multiplication and division) and the numbers are all whole numbers from -100 to 100. The result is allowed to be float. I know the registries work in the same way I.e calculate result of two numbers and store it, than calculate result of stored value and the next operant and store. And so forth until there are no operands left. The number of operands will usually be 2 but I will have a need of 3 or even more so yes, more operands is a requirement.
I was wondering how would you structure this in C#? What tools helper functions you would use in this scenario?
Note: I am working on Unity 5.1.4 project and I want to use a math parser in it. Unity is .NET 2.0
Note: This seems most promising: http://mono.1490590.n4.nabble.com/Javascript-eval-function-in-c-td1490783.html
It uses a variant of eval() function.
In .NET there are no some high level helper functions to help you with this. You would have to parse and tokenize the string in your code. There are however third party libraries that do what you need, for instance Expression Compiler, Simple Math Parser, Mathos Parser, and many other. Search for math expression parser.
If you want to make one from scratch you could look the code of existing ones.
Hans Passant mentions a simple solution, maybe just what you need. You get the result of the expression, so if you need just that, and not the actual expression tokens, then .NET got you covered.
This tool finished the job with no adding external references, dlls or what not: http://mono.1490590.n4.nabble.com/Javascript-eval-function-in-c-td1490783.html
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Evaluate C# string with math operators
So lets say I have a basic string with the value "1*2+4"
How would I go about parsing the information and then doing the calculation?
I am self teaching c# but my assumption is this is a common issue in programming but without using a library how would one do this?
My results so far have got me splitting the string up and putting them into an array of chars, but this is where I've stopped since I am trying to figure out how to compare chars to operators and chars to ints.
I am not sure if I am going the right way about this but would be great if someone could point me in the right direction.
Thank you for your help in advanced.
What you're looking for is the Shunting-yard algorithm.
You'll need at least two stacks; one for storing operators and one for operands. After you fill the stacks you can make a RPN and calculate the answer.
Well c# (or any other language) might provide you with various tools to help you, but the overall approach to the problem will always remain the same whatever the programming language be.
So yes, you do split up into operators & integers. You do recognize the characters one by one, but try to do it in the most efficient way of the language. Fosco's anser points to the right link. Use Ncalc Library than doing manual labor.
However, to complete what you started :
int.Parse(str)
int.TryParse(str, out num)
...are the functions you may consider to convert character strings into integers (which you got, by using split() function?) in C#. You can read about them here...(Parse, TryParse)
If you want to learn how the various existing libraries do it, you should learn about parsing, lexical and syntactic analysis, expression trees, compiler theory, etc. Also, go through the source-code of any of the multiple open-source libraries that do it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Are C# and JavaScript Regular Expressions different?
Is there a list of these differences?
Here's a difference we bumped into that I haven't seen documented anywhere, so I'll publish it, and the solution, here in the hope that it will help someone.
We were testing "some but not all" character classes, such as "A to Z but not Q, V or X", using "[A-Z-[QVX]]" syntax. Don't know where we found it, don't know if it's documented, but it works in .Net.
For example, in Powershell, using the .Net regex class,
[regex]::ismatch("K", "^[A-Z-[QVX]]$")
returns true. Test the same input and pattern in JavaScript and it returns false, but test "K" against "^[A-Z]$" in JavaScript and it returns true.
You can use the more orthodox approach of negative lookahead to express "A to Z but not Q, V or X", eg "^(?![QVX])[A-Z]$", which will work in both Powershell and (modern) JavaScript.
Given Ben Atkin's point above about IE6 and IE7 not supporting lookahead, it may be that the only way to do this in a fool-proof (or IE7-proof) way is to expand the expression out, eg "[A-Z-[QVX]" -> "ABCDEFGHIJKLMNOPRSTUWYZ". Ouch.
First, some resources:
Mozilla Development Center JavaScript Guide: Regular Expressions
.NET Framework Regular Expressions - see the links at the bottom of the page
Here are a few differences:
Lookahead is not supported in IE6 and IE7. (Search for x(?=y) in the MDC guide for for examples.)
JavaScript doesn't support named capture groups. Example: (?<foo>)
The list of metacharacters supported by JavaScript is much shorter.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet.
We'll need to support more 'formats' in the future too.
Do we go for a solution using:
Regex
Simply string searching (using string.IndexOf etc)
Lex/ Yacc
Other
The overall solution will be developed in C# 2.0 (hopefully 3.5)
Regex.
Regex can solve almost everything except for world peace. Well maybe world peace too.
The three solutions you stated each cover very different needs.
Manual parsing (simple text search) is the most flexible and the most adaptable, however, it very quickly becomes a real pain in the ass as the parsing required is more complicated.
Regex are a middle ground, and probably your best bet here. They are powerful, yet flexible as you can yourself add more logic from the code that call the different regex. The main drawback would be speed here.
Lex/Yacc is really only adapted to very complicated, predictable syntaxes and lacks a lot of post compile flexibility. You can't easily change parser in mid parsing, well actually you can but it's just too heavy and you'd be better using regex instead.
I know this is a cliché answer, it all really comes down to what your exact needs are, but from what you said, I would personally probably go with a bag of regex.
As an alternative, as Vaibhav poionted out, if you have several different situations that can arise and that you cna easily detect which one is coming, you could make a plugin system that chooses the right algorithm, and those algorithms could all be very different, one using Lex/Yacc in pointy cases and the other using IndexOf and regex for simpler cases.
You probably should have a pluggable system regardless of which type of string parsing you use. So, this system calls upon the right 'plugin' depending on the type of email to parse it.
You must architect your solution to be updatable, so that you can handle unknown situations when they crop up. Create an interface for parsers that contains not only methods for parsing the emails and returning results in a standard format, but also for examining the email to determine if the parser will execute.
Within your configuration, identify the type of parser you wish to use, set its configuration options, and the configuration for the identifiers which determine if a parser will act or not. Name the parsers by assembly qualified name so that the types can be instantiated at runtime even if there aren't static links to their assemblies.
Identifiers can implement an interface as well, so you can create different types that check for different things. For instance, you might create a regex identifier, which parses the email for a specific pattern. Make sure to make as much information available to the identifier, so that it can make decisions on things like from addresses as well as the content of the email.
When your known parsers can't handle a job, create a new DLL with types that implement the parser and identifier interfaces that can handle the job and drop them in your bin directory.
It depends on what you're parsing. For anything beyond what Regex can handle, I've been using ANTLR. Before you jump into recursive descent parsing for the first time, I would research how they work, before attempting to use a framework like this one. If you subscribe to MSDN Magazine, check the Feb 2008 issue where they have an article on writing one from scratch.
Once you get the understanding, learning ANTLR will be a ton easier. There are other frameworks out there, but ANTLR seems to have the most community support and public documentation. The author has also published The Definitive ANTLR Reference: Building Domain-Specific Languages.
Regex would probably be you bes bet, tried and proven. Plus a regular expression can be compiled.
Your best bet is RegEx because it provides a much greater degree of flexibility than any of the other options.
While you could use IndexOf to handle somethings, you may quickly find yourself writing code that looks like:
if(s.IndexOf("search1")>-1 || s.IndexOf("search2")>-1 ||...
That can be handled in one RegEx statement. Plus, there are a lot of place like RegExLib.com where you can find folks who have shared regular expressions to solve problems.
#Coincoin has covered the bases; I just want to add that with regex it's particularly easy to end up with hard-to-read, hard-to-maintain code. Regex is a powerful and very compact language, so that's how it often goes.
Using whitespace and comments within the regex can go a long way to make it easier to maintain regexes. Eric Gunnerson turned me on to this idea. Here's an example.
Use PCRE. All other answers are just 2nd Best.
With as little information you provided, i would choose Regex.
But what kind of information you want to parse and what you would want to do will change the decision to Lex/Yacc maybe..
But it looks like you've already made your mind up with String search :)