9

How do I delete a trailing period (.) followed by a number (one or two digits in length) directly preceding it? Example:

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

I only want to remove the .45 and the .5.

3 Answers 3

20

You just need a simple regular expression:

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

A few comments:

  1. The first argument in gsub is the pattern we are looking for. The second argument is what to replace it with (in this case, nothing).
  2. The $ character looks for the pattern at the end of the string
  3. [0-9]* looks for 1 or more digits. Alternatively, you could use \\d* or [[:digit:]]*.
  4. \\. matches the full stop. We need to escape the full stop with two slashes.
0
3

Try this

gsub("\\.[[:digit:]]*$", "", z)
-1

The best way to do this is with a regular expression replacement statement. How you do this depends on the language that you are using.

Here's the regex pattern you need to identify the trailing numbers

(.\d{1,2})^

And you should simply replace the matches with ""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.