基于分隔符的字符串拆分

时间:2014-08-25 07:07:01

标签: regex r

我的字符串是

 c("closely-monitored",  "rights-of-way", "THIS_IS_A_CONSTANT")

我喜欢把它分成单独的单词

  "closely" "-monitored", "rights", "-of", "-way", "THIS", "_IS", "_A", "_CONSTANT"

尝试

 paste("\\-", strsplit(str3, "_|-"))

但它不起作用。

1 个答案:

答案 0 :(得分:3)

以下是与perl兼容的正则表达式的方法:

vec <- c("closely-monitored",  "rights-of-way", "THIS_IS_A_CONSTANT")

unlist(strsplit(vec, "(?<=[^-_])(?=[-_])", perl = TRUE))

# [1] "closely"    "-monitored" "rights"     "-of"        "-way"      
# [6] "THIS"       "_IS"        "_A"         "_CONSTANT"