Misha
Misha

Reputation: 173

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"

Upvotes: 1

Views: 1303

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370879

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)

Upvotes: 4

Related Questions