【问题标题】:Split a string AFTER a pattern occurs在模式发生后拆分字符串
【发布时间】:2018-08-22 00:53:29
【问题描述】:

我有以下字符串向量。它包含两个元素。每个元素都由两个折叠的短语组成。

strings <- c("This is a phrase with a NameThis is another phrase",
         "This is a phrase with the number 2019This is another phrase")

我想为向量中的每个元素拆分这些短语。我一直在尝试类似的东西:

library(stringr)

str_split(strings, "\\B(?=[a-z|0-9][A-Z])")

这几乎给了我想要的东西:

[[1]]
[1] "This is a phrase with a Nam" "eThis is another phrase"

[[2]]
[1] "This is a phrase with the number 201" "9This is another phrase"

我想在模式之后进行拆分,但不知道该怎么做。

我想我已经接近解决方案,希望能提供任何帮助。

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    您需要匹配就在大写字母之前的位置,而不是初始短语的最后一个字母之前的位置(即您需要的位置之前的一个字符)。您可能只是将非单词边界与大写字母前瞻匹配:

    str_split(strings, "\\B(?=[A-Z])")
    

    如果短语可以包含前导大写字母,但在小写字母开始后不包含任何大写字母,您也可以将它们拆分为后向查找数字或小写字母。这次不需要非单词边界:

    strings <- c("SHOCKING NEWS: someone did somethingThis is another phrase",
             "This is a phrase with the number 2019This is another phrase")
    str_split(strings, "(?<=[a-z0-9])(?=[A-Z])")
    

    【讨论】:

    • 太棒了!谢谢!我没有举这个例子,但是如果我有一个字符串,比如“令人震惊的新闻:有人做了某事这是另一个短语”怎么办?您能否举一个在这种情况下也会产生预期结果的一般示例?
    • 再次感谢您。我真的很感谢你的帮助。我希望我能再投票一次。
    【解决方案2】:

    替代解决方案。查找一个小写字母或数字后跟一个大写字母,并在两者之间进行拆分。

    strsplit(strings, "(?<=[[:lower:][:digit:]])(?=[[:upper:]])", perl=TRUE)
    
    [[1]]
    [1] "This is a phrase with a Name" "This is another phrase"      
    
    [[2]]
    [1] "This is a phrase with the number 2019" "This is another phrase"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-15
      • 2015-08-30
      • 2013-04-11
      • 1970-01-01
      • 2022-07-12
      • 2019-03-27
      • 2018-11-10
      • 2017-05-07
      相关资源
      最近更新 更多