简体   繁体   中英

regex remove digits after a dot

I'm trying to remove numbers after the dot so that 711.50 becomes 711 without changing the rest of the string. I have some code but it isn't working properly.

str <- "1,300 711.50 1300"
gsub("\\.\\d+$", "", str)

Desired output: "1,300 711 1300"

The $ in "\\\\.\\\\d+$" requires the repeated digits after the literal . to finish at the end of a line . But you have 1300 after 711.50 , so the regular expression does not match the string. Remove the $ and it works as expected:

str <- "1,300 711.50 1300"
gsub("\\.\\d+", "", str)

(Your original regular expression would work if your input str was "1,300 711.50" , with the .50 at the end of the line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM