【问题标题】:Insert characters when a string changes its case R当字符串改变大小写时插入字符 R
【发布时间】:2020-08-29 16:36:49
【问题描述】:

我想在字符串中插入字符的地方改变它的大小写。我尝试在固定数量的字符之后插入一个'\n',然后是一个'',因为我不知道如何检测大小写变化

s <-c("FloridaIslandE7", "FloridaIslandE9", "Meta")
gsub('^(.{7})(.{6})(.*)$', '\\1\\\n\\2 \\3', s )

[1] "Florida\nIsland E7" "Florida\nIsland E9" "Meta"     

这是有效的,因为位置是固定的,但我想知道在一般情况下如何做。

【问题讨论】:

    标签: r regex string


    【解决方案1】:

    当然有一个不那么复杂的regex,但你可以试试:

    gsub('([A-Z][0-9])', ' \\1', gsub('([a-z])([A-Z])', '\\1\n\\2', s))
    

    输出:

    [1] "Florida\nIsland E7" "Florida\nIsland E9" "Meta"    
    

    【讨论】:

      【解决方案2】:

      这是一个选项

      str_replace_all(s, "(?<=[a-z])(?=[A-Z])", "\n")
      #[1] "Florida\nIsland\nE7" "Florida\nIsland\nE9" "Meta" 
      

      【讨论】:

        【解决方案3】:

        如果你真的想插入\n,试试这个:

        gsub("([a-z])([A-Z])", "\\1\\\n\\2", s)
        [1] "Florida\nIsland\nE7" "Florida\nIsland\nE9" "Meta"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-07
          • 2021-11-14
          • 2017-08-02
          • 1970-01-01
          • 2014-02-04
          • 1970-01-01
          • 1970-01-01
          • 2016-01-25
          相关资源
          最近更新 更多