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
.
The regex \\. $ removes a dot (after escaping with the double backslashes) at the end of the 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.
You just need a simple regular expression:
z_new = gsub("\\.[0-9]*$", "", z)
A few comments:
$
character looks for the pattern at the end of the string[0-9]*
looks for 1 or more digits. Alternatively, you could use \\d*
or [[:digit:]]*
.\\.
matches the full stop. We need to escape the full stop with two slashes.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With