将角色分成几部分 [英] Spliting the character into parts
问题描述
我观察到以下字符:
l <- "mod, range1 = seq(-m, n, 0.1), range2 = seq(-2, 2, 0.1), range3 = seq(-2, 2, 0.1)"
在R中使用正则表达式我希望将l
拆分为以下结构:
Using regular expressions in R I desire to split l
in the following structure:
[1] "mod" "range1 = seq(-m, n, 0.1)"
[3] "range2 = seq(-2, 2, 0.1)" "range3 = seq(-2, 2, 0.1)"
不幸的是,我还没有找到解决问题的合适方法.任何人都有一个想法如何获得这种选举分裂?
Unfortunetely, I didn't find a proper way to overcome the problem, yet. Anyone has an idea how is it possible to acquire such an elegeant split?
推荐答案
我真的怀疑您可以使用正则表达式来做到这一点.您正在尝试解析您的字符串,因此您需要一个解析器,该解析器通常比正则表达式更强大.我认为它不够通用,但是您可以利用R解析器和alist
类.试试:
I really doubt you can do it with regular expression. You are trying to parse your string and so you need a parser, which is generally more powerful than a regex. I don't think it's general enough, but you can take advantage of the R parser and the alist
class. Try:
res<-eval(parse(text=paste0("alist(",l,")")))
paste0(names(res),ifelse(names(res)!="","=",""),as.character(res))
#[1] "mod" "range1=seq(-m, n, 0.1)" "range2=seq(-2, 2, 0.1)"
#[4] "range3=seq(-2, 2, 0.1)"
请记住,如果有嵌套括号,则regex建议的解决方案将失败.尝试一下并使用以下方法进行挖掘:
Keep in mind that the regex proposed solutions fail if there are nested brackets. Try them and mine with:
l<-"mod, range1 = seq(-m, n, 0.1), range2 = seq(-2, exp(2), 0.1), range3 = seq(-2, 2, 0.1)"
了解我的意思.
这篇关于将角色分成几部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!