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 this but was unsuccessful.
N <- c("59.22.07", "58.01.32", "57.26.49")
#my attempts:
gsub("(!?\\.)", "", N)
gsub("([\\.]?!)", "", N)
How could we remove the last period in the string to get:
[1] "59.2207" "58.0132" "57.2649"
Maybe this reads a little better:
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: