如何在 Julia 中解析多行字符串? [英] How to parse multiline string in Julia?
本文介绍了如何在 Julia 中解析多行字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何解析更多行代码?
这是有效的:
julia> eval(parse("""print("O");print("K")"""))
OK
这不起作用:
julia> eval(parse("""print("N");
print("O")"""))
ERROR: ParseError("extra token after end of expression")
Stacktrace:
[1] #parse#235(::Bool, ::Function, ::String) at ./parse.jl:237
[2] parse(::String) at ./parse.jl:232
顺便说一句,如果我逐行尝试,我还有其他问题.例如:
BTW if I try line by line I have other problems. For example:
julia> parse("""for i in 1:3""")
:($(Expr(:incomplete, "incomplete: premature end of input")))
虽然:
julia> eval(parse("""for i in 1:2
println(i)
end"""))
1
2
推荐答案
parse
旨在解析单个表达式(至少文档是这么说的:鉴于此,我实际上有点惊讶您的第一个示例有效,不会引发错误...).
parse
is designed to parse a single expression (at least that's what the docs say: given this I'm actually a bit surprised your first example works , without throwing an error...).
如果你想解析多个表达式,那么你可以利用以下事实:
If you want to parse mutliple expressions then you can take advantage of the fact that:
parse
可以接受第二个参数start
告诉它在哪里开始解析.- 如果您提供此起始参数,则它会返回一个包含表达式的元组,以及表达式完成的位置.
parse
can take a second argumentstart
that tells it where to start parsing from.- If you provide this start argument then it returns a tuple containing the expression, and where the expression finished.
自己定义一个 parseall
函数.曾经有一个在基地,但我不确定是否还有.仍有测试见下文
to define a parseall
function yourself. There used to be one in base but I'm not sure there is anymore. there is still in the tests see below
# modified from the julia source ./test/parse.jl
function parseall(str)
pos = start(str)
exs = []
while !done(str, pos)
ex, pos = parse(str, pos) # returns next starting point as well as expr
ex.head == :toplevel ? append!(exs, ex.args) : push!(exs, ex) #see comments for info
end
if length(exs) == 0
throw(ParseError("end of input"))
elseif length(exs) == 1
return exs[1]
else
return Expr(:block, exs...) # convert the array of expressions
# back to a single expression
end
end
这篇关于如何在 Julia 中解析多行字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文