Javascript解析器,用于简单表达 [英] Javascript parser for simple expression

查看:141
本文介绍了Javascript解析器,用于简单表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一个可以处理和评估简单表达式的JavaScript解析器。解析器应该能够评估常规的数学表达式,并使用参数支持自定义函数。它还必须支持字符串处理。字符串连接与||操作员支持是首选,但是如果+将会做到这一点,这是可以的。

I would like to find a javascript parser that can handle and evaluate simple expressions. The parser should be able to evaluate the regular mathematical expressions, and support custom functions with parameters. It also has to support strings handling. String concatenation with || operator support is preferred, but it is okay if + will do the trick.

解析器应该处理的表达式示例:

Examples of an expression that should be handled by the parser:

3 *(2 + 1) - 1

3 * (2 + 1) - 1

2 * func(2,2)

2 * func(2, 2)

func('hello world',0,5)|| '你'

func('hello world', 0, 5) || ' you'

有没有人实现过这样的事情,或者在哪里可以找到类似的东西?

Has anyone implemented such a thing or where can I find something similar?

推荐答案

我有一个 ActionScript解析器的修改版本AS,不解析AS)支持自定义函数,但不支持字符串。这可能很容易添加字符串支持。我会将其上传到某个地方,以便您可以在 http://silentmatt.com/parser2.js http://silentmatt.com/parser3.js

I have a modified version of an ActionScript parser (written in AS, not parses AS) that supports custom functions, but not strings. It would probably be easy to add string support though. I'll upload it somewhere so you can get it at http://silentmatt.com/parser2.js http://silentmatt.com/parser3.js.

编辑:我很容易添加了对字符串的基本支持。它不支持转义序列,并且JSFunction不起作用,但只需要几分钟即可使其工作。将连接运算符更改为||应该很简单。

I added basic support for strings pretty easily. It doesn't support escape sequences and toJSFunction doesn't work, but it only took a few minutes to get it working. Changing the concatenation operator to "||" should be pretty easy too.

以下是评估示例表达式的方法:

Here's how you would evaluate your example expressions:

js> var parser = new Parser();
js> parser.parse("3 * (2 + 1) - 1").evaluate();
8
js> parser.parse("2 * func(2; 2)").evaluate({ func:Math.pow });
8
js> function substr(s, start, end) { return s.substring(start, end); }
js> parser.parse("func('hello world'; 0; 5) + ' you'").evaluate({ func:substr });
hello you

我不记得为什么我用分号作为参数分隔符;我认为它与区分功能和内置的操作符功能有关。

I don't remember why I used semicolons as argument separators; I think it has something to do with differentiating between functions and built-in "operator" functions.

另一个编辑:

我一直在玩这个,现在在 http://silentmatt.com/parser3.js (toJSFunction工作,您可以使用标准的JavaScript转义序列)。它还使用逗号分隔所有函数的参数,并将 || 作为字符串连接运算符而不是 + 没有添加。

I've been playing with this a little, and now there's a version with better string support at http://silentmatt.com/parser3.js (toJSFunction works, and you can use standard JavaScript escape sequences). It also uses commas to separate arguments for all functions and || as the string concatenation operator instead of +, which only does addition.

这篇关于Javascript解析器,用于简单表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆