Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a period and a number at the end of a character string

Tags:

regex

r

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.

like image 630
Braden Avatar asked Aug 07 '12 15:08

Braden


People also ask

How do you remove a period at the end of a string?

The regex \\. $ removes a dot (after escaping with the double backslashes) at the end of the string.

How do I remove part of a string?

We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove. REMOVE(): This function replaces all occurrences of a substring within a new substring.


1 Answers

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.
like image 73
csgillespie Avatar answered Oct 25 '22 22:10

csgillespie