我正在尝试使用 stringi
要在分隔符上拆分的包(可能重复定界符),但保留分隔符。这类似于我问卫星前的这个问题: R拆分分隔符(拆分)保留分隔符(拆分) 但是分隔符可以重复。我不认为基地 strsplit
可以处理这种类型的正则表达式。该 stringi
包可以,但我无法弄清楚如何格式正则表达式,如果有重复,它分裂在分隔符上,也不会在字符串的末尾留下空字符串。
基本R解决方案,stringr,stringi等解决方案都受到欢迎。
后来的问题发生是因为我使用贪婪 *
在...上 \\s
但是这个空间并没有很大的空间,所以我只想把它留在:
MWE
text.var <- c("I want to split here.But also||Why?",
"See! Split at end but no empty.",
"a third string. It has two sentences"
)
library(stringi)
stri_split_regex(text.var, "(?<=([?.!|]{1,10}))\\s*")
#结果
## [[1]]
## [1] "I want to split here." "But also|" "|" "Why?"
## [5] ""
##
## [[2]]
## [1] "See!" "Split at end but no empty." ""
##
## [[3]]
## [1] "a third string." "It has two sentences"
# 期望的结果
## [[1]]
## [1] "I want to split here." "But also||" "Why?"
##
## [[2]]
## [1] "See!" "Split at end but no empty."
##
## [[3]]
## [1] "a third string." "It has two sentences"