3

I have a string vector that looks like this and I'd like to split it up:

str <- c("Fruit LoopsJalapeno Sandwich", "Red Bagel", "Basil LeafBarbeque SauceFried Beef")

str_split(str, '[a-z][A-Z]', n = 3)

[[1]]
[1] "Fruit Loop"       "alapeno Sandwich"

[[2]]
[1] "Red Bagel"

[[3]]
[1] "Basil Lea"    "arbeque Sauc" "ried Beef"

But I need to keep those letters at the end and start of the words.

4

2 回答 2

5

这是 base 中的 2 种方法(如果需要,您可以推广到stringr)。

这个用一个占位符代替这个地方,然后在那个地方分裂。

strsplit(gsub("([a-z])([A-Z])", "\\1SPLITHERE\\2", str), "SPLITHERE")

## [[1]]
## [1] "Fruit Loops"       "Jalapeno Sandwich"
## 
## [[2]]
## [1] "Red Bagel"
## 
## [[3]]
## [1] "Basil Leaf"     "Barbeque Sauce" "Fried Beef"  

此方法使用前瞻和后瞻:

strsplit(str, "(?<=[a-z])(?=[A-Z])", perl=TRUE)

## [[1]]
## [1] "Fruit Loops"       "Jalapeno Sandwich"
## 
## [[2]]
## [1] "Red Bagel"
## 
## [[3]]
## [1] "Basil Leaf"     "Barbeque Sauce" "Fried Beef"  

编辑概括为stringr ,因此您可以根据需要抓取 3 件

stringr::str_split(gsub("([a-z])([A-Z])", "\\1SPLITHERE\\2", str), "SPLITHERE", 3)
于 2015-02-21T22:45:12.607 回答
3

You could also match instead of splitting based off your string.

unlist(regmatches(str, gregexpr('[A-Z][a-z]+ [A-Z][a-z]+', str)))
# [1] "Fruit Loops"       "Jalapeno Sandwich" "Red Bagel"        
# [4] "Basil Leaf"        "Barbeque Sauce"    "Fried Beef" 
于 2015-02-21T23:10:59.877 回答