Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove character string only if it occurs at the end of a string

I want to remove the final characters "txt" if they exist at the end of a character string. However, sometimes, the characters can be found at other locations of the string also.

i.e. I would like to remove txt from "/some-text-here/txt" but not from "/txt-not-to-remove-text/" since in the last example it does not occur after the last occurance of the /

So, I only want to extract txt if it occurs at the end of the string.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

string = c("/some-text-here/txt",
           "/some-other-text-here/txt",
           "/txt-not-to-remove-text/",
           "/txt-another-line-of-text/txt")

>Solution :

We may use trimws

trimws(string, whitespace = "/txt", which = 'right')

-output

[1] "/some-text-here"           "/some-other-text-here"  
[3]   "/txt-not-to-remove-text/"  "/txt-another-line-of-text"

Or using sub and specify the end ($) of the string

sub("/txt$", "", string)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading