Remove all characters before a period in a string

前端 未结 5 1631
独厮守ぢ
独厮守ぢ 2020-12-09 18:01

This keeps everything before a period:

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

how to keep everything after the period?

相关标签:
5条回答
  • 2020-12-09 18:15

    require(stringr)

    I run a course on Data Analysis and the students came up with this solution :

    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) 
    
            }
    

    Now, just call the function :

    my_vector <-  c('foobar.barfoo', 'amazing.point')
    
    get_after_period(my_vector)
    
    [1] "barfoo" "point"
    
    0 讨论(0)
  • 2020-12-09 18:16

    To remove all the characters before a period in a string(including period).

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

    Example:

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

    To remove all the characters before the first period(including period).

    > data <- 'foo.bar.barfoo'
    > gsub("^.*?\\.","", data)
    [1] "bar.barfoo"
    
    0 讨论(0)
  • 2020-12-09 18:20

    use this :

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

    this will keep everything after period

    0 讨论(0)
  • 2020-12-09 18:34

    You could use stringi with lookbehind regex

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

    If the string doesn't have ., this retuns NA (it is not clear about how to deal with this in the question)

     stri_extract_first_regex(data2, "(?<=\\.).*")
     #[1] NA
    
    ###data
    data <- 'foobar.barfoo' 
    data1 <- 'foo.bar.barfoo'
    data2 <- "foobar"
    
    0 讨论(0)
  • 2020-12-09 18:37

    If you don't want to think about the regex for this the qdap package has the char2end function that grabs from a particular character until the end of the string.

    data <- c("foo.bar", "foo.bar.barfoo")
    
    library(qdap)
    char2end(data, ".")
    
    ## [1] "bar"        "bar.barfoo"
    
    0 讨论(0)
提交回复
热议问题