如何从R解析R语法?

Jan*_*ary 2 regex parsing r

我试图通过分析R历史,将一个跟踪对象历史的小脚本放在一起.我坚持有效地解析R命令并拆分它们.考虑以下R命令:

for( i in 1:10 ) { a[i] <- myfunc() ; print( sprintf( "done step %d; proceeding", i ) )  }
Run Code Online (Sandbox Code Playgroud)

用分号或大括号分割不是问题,但是引号中的分号(或其他特殊事物)呢?我最终通过char去查询char并跟踪我是否在引用中(以及反斜杠......).这是步法,我确信有一些更简单的东西,可能是在Unix诞生的时候发明的.也许是一个聪明的正则表达式?

Jam*_*mes 5

使用parse.它返回一个表达式,可以将其子集化到解析树的各个组件中:

x <- parse(text='for( i in 1:10 ) { a[i] <- myfunc() ; print( sprintf( "done step %d; proceeding", i ) )  }',n=1)


x[[1]]
for (i in 1:10) {
    a[i] <- myfunc()
    print(sprintf("done step %d; proceeding", i))
}

x[[1]][[1]]
`for`

x[[1]][[4]]
{
    a[i] <- myfunc()
    print(sprintf("done step %d; proceeding", i))
}

x[[1]][[4]][[2]]
a[i] <- myfunc()
Run Code Online (Sandbox Code Playgroud)