2017-10-20 99 views
1

我有一個問題,提取函數的參數在R.正則表達式來提取函數的參數中的R

x="theme(legend.position='bottom', 
    legend.margin=(t=0,r=0,b=0,l=0,unit='mm'), 
    legend.background=element_rect(fill='red',size=rel(1.5)), 
    panel.background=element_rect(fill='red'), 
    legend.position='bottom')" 

我要的是:

[1]legend.position='bottom' 
[2]legend.margin=(t=0,r=0,b=0,l=0,unit='mm') 
[3]legend.background=element_rect(fill='red',size=rel(1.5)) 
[4]panel.background=element_rect(fill='red') 
[5]legend.position='bottom' 

我試了幾個正則表達式都沒有成功,包括以下:

strsplit(x,",(?![^()]*\\))",perl=TRUE)

請幫幫我!

+4

我會帶你回去一步。你是如何以R/ggplot代碼保存爲文本的?我猜在這裏首先應該有一個更簡單的方法.. – thelatemail

+0

其實我正在製作一個閃亮的godget來教ggplot2。我將把這個閃亮的應用程序變成RStudio插件包,並在幾天內在CRAN上發佈。 –

+0

我在嘗試,但它有點複雜 – pirs

回答

0

Arf的,我真的很抱歉,但我必須去工作,我會在稍後繼續,但現在我只是讓我的方式來部分解決它:theme\(([a-z.]*=['a-z]*)|([a-z._]*=[a-z0-9=,'_.()]*)*\,\)?

它忽略只有最後一部分。這

這裏的regex101頁面:https://regex101.com/r/BZpcW0/2

待會兒見。

+0

非常感謝。我正在嘗試。 –

1

我想這裏的最佳答案可能是而不是嘗試使用正則表達式來分析函數調用。顧名思義,正則表達式需要常規語言。你的函數調用是不規則的,因爲它有嵌套的括號。我目前看到最大嵌套深度爲2,但是誰知道在某個點上它是否會變得更深。

我建議改爲編寫一個簡單的解析器。您可以在這裏使用堆棧來跟蹤括號。如果所有圓括號都關閉,則只會關閉一個參數,這意味着您不在參數的中間,除了可能是第一個參數。

0

謝謝你的一切建議。我已經解析了句子,並得到了列表中的參數。這是我的解決方案。

x<-"theme(legend.margin=margin(t=0,r=0,b=0,l=0,unit='mm'), 
legend.background=element_rect(fill='red',size=rel(1.5)), 
panel.background=element_rect(fill='red'), 
legend.position='bottom')" 

extractArgs=function(x){ 

result<-tryCatch(eval(parse(text=x)),error=function(e) return("error")) 

if("character" %in% class(result)){ 
    args=character(0) 
} else { 
    if(length(names(result)>0)){ 
     pos=unlist(str_locate_all(x,names(result))) 
     pos=c(sort(pos[seq(1,length(pos),by=2)]),nchar(x)+1) 

     args=c() 
     for(i in 1:(length(pos)-1)){ 
     args=c(args,substring(x,pos[i],lead(pos)[i]-2)) 
     } 

    } else{ 
     args=character(0) 
    } 
} 
args 
}