【问题标题】:Remove all characters before a period in a string删除字符串中句点之前的所有字符
【发布时间】:2014-09-23 09:42:32
【问题描述】:

这样可以保留句号之前的所有内容:

gsub("\\..*","", data$column )

经期后如何保留一切?

【问题讨论】:

  • .*?\\. 应该这样做。
  • 如果只有一个句点,使用否定。 ^[^.]*\\.

标签: regex r string


【解决方案1】:

删除字符串中句点之前的所有字符(包括句点)。

gsub("^.*\\.","", data$column )

例子:

> data <- 'foobar.barfoo'
> gsub("^.*\\.","", data)
[1] "barfoo"

删除第一个句号之前的所有字符(包括句号)。

> data <- 'foo.bar.barfoo'
> gsub("^.*?\\.","", data)
[1] "bar.barfoo"

【讨论】:

    【解决方案2】:

    您可以将stringilookbehind 正则表达式一起使用

     library(stringi)
     stri_extract_first_regex(data1, "(?<=\\.).*")
     #[1] "bar.barfoo"
     stri_extract_first_regex(data, "(?<=\\.).*")
     #[1] "barfoo"
    

    如果字符串没有.,则返回NA(问题中不清楚如何处理)

     stri_extract_first_regex(data2, "(?<=\\.).*")
     #[1] NA
    
    ###data
    data <- 'foobar.barfoo' 
    data1 <- 'foo.bar.barfoo'
    data2 <- "foobar"
    

    【讨论】:

      【解决方案3】:

      如果您不想为此考虑正则表达式,qdap 包具有 char2end 函数,该函数从特定字符抓取直到字符串结尾。

      data <- c("foo.bar", "foo.bar.barfoo")
      
      library(qdap)
      char2end(data, ".")
      
      ## [1] "bar"        "bar.barfoo"
      

      【讨论】:

        【解决方案4】:

        使用这个:

        gsub(".*\\.","", data$column )
        

        这将保留期间后的所有内容

        【讨论】:

          【解决方案5】:

          require(stringr)

          我开设了一门数据分析课程,学生们想出了这个解决方案:

          get_after_period <- function(my_vector) {    
          
                  # Return a string vector without the characters
                  # before a period (excluding the period)
          
                  # my_vector, a string vector
          
                  str_sub(my_vector, str_locate(my_vector, "\\.")[,1]+1) 
          
                  }
          

          现在,只需调用函数:

          my_vector <-  c('foobar.barfoo', 'amazing.point')
          
          get_after_period(my_vector)
          
          [1] "barfoo" "point"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-01-26
            • 2011-06-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多