regex - return all before the second occurrence

前端 未结 4 1414
天命终不由人
天命终不由人 2020-12-08 11:17

Given this string:

DNS000001320_309.0/121.0_t0

How would I return everything before the second occurrence of \"_\"?

DNS0000         


        
4条回答
  •  执笔经年
    2020-12-08 11:57

    Personally, I hate regex, so luckily there's a way to do this without them, just by splitting the string:

    > s <- "DNS000001320_309.0/121.0_t0"      
    > paste(strsplit(s,"_")[[1]][1:2],collapse = "_")
    [1] "DNS000001320_309.0/121.0"
    

    Although of course this assumes that there will always be at least 2 underscores in your string, so be careful if you vectorize this and that isn't the case.

提交回复
热议问题