Remove the period and number at the end of the character string

How to remove a number (one or two digits in length) and a point located immediately in front of it, every time it occurs at the end of a line in a certain variable in R ? Example:

 z<-c("awe", "p.56.red.45", "ted.5", "you.88.tom") 

I want to remove only .45 and .5 .

+6
source share
3 answers

You just need a simple regex:

 z_new = gsub("\\.[0-9]*$", "", z) 

A few comments:

  • The first argument to gsub is the template we are looking for. The second argument is that replacing it (in this case nothing).
  • The character $ looking for a pattern at the end of the line
  • [0-9]* searches for 1 or more digits. Alternatively, you can use \\d* or [[:digit:]]* .
  • \\. corresponds to a complete stop. We need to avoid a complete stop with two slashes.
+16
source

try it

 gsub("\\.[[:digit:]]*$", "", z) 
+3
source

The best way to do this is with the regex operator. How you do this depends on the language you use.

Here is the regex pattern you need to identify the final numbers

(. \ D {1,2}) ^

And you just have to replace the matches

-1
source

Source: https://habr.com/ru/post/922297/


All Articles