Remove last occurrence of character

前端 未结 4 1341
醉梦人生
醉梦人生 2021-02-07 11:58

A question came across talkstats.com today in which the poster wanted to remove the last period of a string using regex (not strsplit). I made an attempt to do thi

4条回答
  •  时光说笑
    2021-02-07 12:11

    Maybe this reads a little better:

    gsub("(.*)\\.(.*)", "\\1\\2", N)
    [1] "59.2207" "58.0132" "57.2649"
    

    Because it is greedy, the first (.*) will match everything up to the last . and store it in \\1. The second (.*) will match everything after the last . and store it in \\2.

    It is a general answer in the sense you can replace the \\. with any character of your choice to remove the last occurence of that character. It is only one replacement to do!

    You can even do:

    gsub("(.*)\\.", "\\1", N)
    

提交回复
热议问题