【问题标题】:Split keep repeated delimiter拆分保持重复的分隔符
【发布时间】:2014-12-18 00:51:18
【问题描述】:

我正在尝试使用 stringi 包在分隔符上拆分(可能会重复分隔符)但保留分隔符。这类似于我之前问过的这个问题:R split on delimiter (split) keep the delimiter (split),但分隔符可以重复。我不认为 base strsplit 可以处理这种类型的正则表达式。 stringi 包可以,但我不知道如何格式化正则表达式,如果有重复,它会在分隔符上拆分,并且不要在字符串末尾留下空字符串。

欢迎使用 Base 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"

【问题讨论】:

    标签: regex r string stringi


    【解决方案1】:

    使用strsplit

     strsplit(text.var, "(?<=[.!|])( +|\\b)", perl=TRUE)
     #[[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"
    

    或者

     library(stringi)
     stri_split_regex(text.var, "(?<=[.!|])( +|\\b)")
     #[[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"
    

    【讨论】:

    • 您介意解释一下*SKIP*F 是什么,以及它们在正则表达式中扮演的角色吗?
    • @Josh O'Brien 感谢 cmets。实际上,不需要*SKIP *F。我之前在编写代码时使用它,后来没有检查它。
    • @Tyle Rinker 谢谢。 *SKIP *F 部分也不能与 stringi 一起使用。
    • 两种方法都很好用,但这个更简洁一些。谢谢+1
    【解决方案2】:

    只需使用一种模式来查找字符间位置:(1) 前面有 ?.!| 之一;和 (2) 后跟?.!| 之一。添加\\s* 以匹配并吃掉任意数量的连续空格字符,您就可以开始了。

    ##                  (look-behind)(look-ahead)(spaces)
    strsplit(text.var, "(?<=([?.!|]))(?!([?.!|]))\\s*", perl=TRUE)
    # [[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"
    

    【讨论】:

    • 您向我展示了我的正则表达式思维错误的地方,这对学习有很大帮助。 akrun 的方法更简洁一些。 +1
    猜你喜欢
    • 2010-11-11
    • 1970-01-01
    • 2012-01-10
    • 2018-11-28
    • 1970-01-01
    • 2017-07-24
    • 2020-10-03
    • 2018-04-10
    • 2020-10-26
    相关资源
    最近更新 更多