R拆分分隔符(拆分)保留分隔符(拆分)

时间:2014-02-01 01:38:41

标签: regex string r split

在R中,您可以使用strsplit函数在分隔符(split)上拆分向量,如下所示:

x <- "What is this?  It's an onion.  What! That's| Well Crazy."
unlist(strsplit(x, "[\\?\\.\\!\\|]", perl=TRUE))

## [1] "What is this"    "  It's an onion" "  What"          " That's"        
## [5] " Well Crazy"

我想使用R保留分隔符(split)。所以期望的输出是:

## [1] "What is this?"    "  It's an onion." "  What!"          " That's|"        
## [5] " Well Crazy."

1 个答案:

答案 0 :(得分:17)

您可以使用"(?<=DELIMITERS)"

unlist(strsplit(x, "(?<=[?.!|])", perl=TRUE))

## [1] "What is this?"    "  It's an onion." "  What!"          " That's|"        
## [5] " Well Crazy.