如何在Julia中解析多行字符串? [英] How to parse multiline string in Julia?
问题描述
如何解析更多代码行?
How can I parse more lines of code?
这有效:
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屋!