Krantz
Krantz

Reputation: 1503

How to replace only characters located between numbers and leave unchanged those with different locations

How to replace "." that is located within numbers with ",", but not replace "." located elsewhere?

Input data:

x_input="23.344,) abcd, 12899.2, (,  efg; abef. gfdc."

Expected ouput:

x_output
"23,344,) abcd, 12899,2, (,  efg; abef. gfdc."

I tried:

x_input<-"23.344,) abcd, 12899.2, (,  efg; abef. gfdc."
x_output<-gsub(".", ",", x_input))))

But this does not work.

Thanks in advance.

Upvotes: 1

Views: 136

Answers (2)

PaulS
PaulS

Reputation: 25528

A possible solution, based on stringr::str_replace_all:

library(tidyverse)

x_input="23.344,) abcd, 12899.2, (,  efg; abef. gfdc."

x_input %>% 
  str_replace_all("(?<=\\d)\\.(?=\\d)", ",")

#> [1] "23,344,) abcd, 12899,2, (,  efg; abef. gfdc."

Or, in base R,

gsub("(?<=\\d)\\.(?=\\d)", ",", x_input, perl = T)

#> [1] "23,344,) abcd, 12899,2, (,  efg; abef. gfdc."

Upvotes: 3

G. Grothendieck
G. Grothendieck

Reputation: 270378

Replace a digit, dot and digit with the first digit, a comma and the second digit.

(Alternately use the pattern

r"{(\d)\.(\d?)}"

if it is sufficient to have a digit before the dot but not after the dot.)

No packages are used.

gsub(r"{(\d)\.(\d)}", r"{\1,\2}", x_input)
## [1] "23,344,) abcd, 12899,2, (,  efg; abef. gfdc."

Upvotes: 3

Related Questions