How to extract everything until first occurrence of pattern

前端 未结 4 1703
夕颜
夕颜 2021-02-19 00:22

I\'m trying to use the stringr package in R to extract everything from a string up until the first occurrence of an underscore.

What I\'ve tried

4条回答
  •  长发绾君心
    2021-02-19 01:03

    You can use sub from base using _.* taking everything starting from _.

    sub("_.*", "", "L0_123_abc")
    #[1] "L0"
    

    Or using [^_] what is everything but not _.

    sub("([^_]*).*", "\\1", "L0_123_abc")
    #[1] "L0"
    

    or using substr with regexpr.

    substr("L0_123_abc", 1, regexpr("_", "L0_123_abc")-1)
    #substr("L0_123_abc", 1, regexpr("_", "L0_123_abc", fixed=TRUE)-1) #More performant alternative
    #[1] "L0"
    

提交回复
热议问题