[英]Regular Expression to extract function arguments in 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)
請幫我!
我認為這里最好的答案可能是不要嘗試使用正則表達式來解析您的函數調用。 顧名思義,正則表達式需要正則語言。 您的函數調用不是常規的,因為它有嵌套的括號。 我目前看到最大嵌套深度為 2,但誰知道這是否會在某個時候變得更深。
我建議改為編寫一個簡單的解析器。 您可以在此處使用堆棧來跟蹤括號。 如果所有括號都關閉,您只會拆分參數,這意味着您不在參數的中間,可能除了第一個。
Arf,我真的很抱歉,但我必須去工作,我會稍后繼續,但現在我只是讓我的方式部分解決它: theme\\(([az.]*=['az]*)|([az._]*=[a-z0-9=,'_.()]*)*\\,\\)?
它只錯過了最后一部分..
這里是 regex101 頁面: https ://regex101.com/r/BZpcW0/2
回頭見。
謝謝你的所有建議。 我已經解析了句子並將參數作為列表。 這是我的解決方案。
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.