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 middle 0 in string preserving trailing 0s

Similar to this question, I want to remove only middle zero’s while preserving trailing zeroes:

testdata <- c("101", "102", "103", "104", "105", "106", "107", "108", "109", "110")

The desired result is 11, 12, 13, 14, 15, 16, 17, 18, 19, 110. My real dataset contains values from 100 to 899 and is in character format.

When I adjust the answer to the linked question, it removes trailing zeroes.

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

sub("([1-8])0(.*)", "\\1\\2", testdata)

returns:

"11" "12" "13" "14" "15" "16" "17" "18" "19" "11"

How can I remove only middle zeroes and leave trailing zeroes?

>Solution :

.* matches any number of characters, including 0. Since you want to explicitly match the last digit, use the same kind of thing you did to match the first:

([1-8])0([0-9])
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