2017-01-13 165 views
-2

我找到了类似的问题here,但它并未真正回答我的问题。在R中拆分字符串并在两个符号中拆分字符

我有一个这样的字符串:

{a,b,c,d}{e,f,g,h}

而且我想这个字符串分割成两个向量:a,b,c,de,f,g,h

我怎么能在R中做到这一点?

非常感谢你,

+1

你至少试过解决方案吗?请发布您的代码并描述出了什么问题。 –

回答

0

您需要两次分割你的字符串:

split1 <- setdiff(strsplit("{a,b,c,d}{e,f,g,h}", "[{}]")[[1]], "") # setdiff permits to suppress the 2 empty strings generated 
split1 
#[1] "a,b,c,d" "e,f,g,h" 

strsplit(split1, ",") 
#[[1]] 
#[1] "a" "b" "c" "d" 
#[[2]] 
#[1] "e" "f" "g" "h" 

2次分裂后,你得到的载体列表你想

1

另一种方式:

regmatches(txt, gregexpr("(?<={)[^}]+", txt, perl=TRUE))

请参阅here.

+0

按照这种方法,regmatches(txt,gregexpr(“(?<= {)[^}] +”,txt,perl = TRUE))'就足够了。 –

+0

太棒了,谢谢! –