如何替换"它位于带有","但不能替换";位于其他位置吗?
输入数据:
x_input="23.344,) abcd, 12899.2, (, efg; abef. gfdc."
预期输出:
x_output
"23,344,) abcd, 12899,2, (, efg; abef. gfdc."
我试着:
x_input<-"23.344,) abcd, 12899.2, (, efg; abef. gfdc."
x_output<-gsub(".", ",", x_input))))
但是这行不通。
提前感谢。
用第一个数字、逗号和第二个数字代替数字、点和数字。
(或者使用模式
)r"{(d).(d?)}"
如果在点前有一个数字而不是在点后有一个数字就足够了。)
不使用包。
gsub(r"{(d).(d)}", r"{1,2}", x_input)
## [1] "23,344,) abcd, 12899,2, (, efg; abef. gfdc."
一个可能的解决方案,基于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."
或者,在base R
中,
gsub("(?<=\d)\.(?=\d)", ",", x_input, perl = T)
#> [1] "23,344,) abcd, 12899,2, (, efg; abef. gfdc."