如何编写用于字符串等算术运算的Scala解析器? [英] How to write an Scala parser for arithmetic operations including string?
本文介绍了如何编写用于字符串等算术运算的Scala解析器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Scala组合器解析进行解析和算术运算其中至少一个变量是字符串.我是scala的初学者,我喜欢它的这一功能!
例如,我想解析:
(数字+ 2)* 4
I am trying to use Scala Combinator-Parsing to parse and arithmetic operation in which at least one of the variables is string. I am a beginner in scala and I like this feature of it!
For instance I wanna parse:
(number + 2) * 4
它是解析数字(带括号的浮点数和整数)的一个很好的例子,
It has a good example of parsing numbers (float and integer with parenthesis) like:
class Arith extends JavaTokenParsers {
def expr: Parser[Any] = term~rep("+"~term | "-"~term)
def term: Parser[Any] = factor~rep("*"~factor | "/"~factor)
def factor: Parser[Any] = floatingPointNumber | "("~expr~")"
}
这是一个字符串:
object MyParsers extends RegexParsers {
val ident: Parser[String] = """[a-zA-Z_]\w*""".r
}
如何更改第一部分以解析数字旁边的字符串?
how can I change the first part to parse string beside numbers?
推荐答案
我认为您应该将其添加到替代因子中:
I think you should add it to the factor alternatives:
def factor: Parser[Any] = ident | floatingPointNumber | "("~expr~")"
这篇关于如何编写用于字符串等算术运算的Scala解析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文