R 查找并替换括号内的值[重复]

问题描述 投票:0回答:1

我想替换方括号内的字符串中的逗号无法找到解决方案我该如何使用 R 任何人请帮助我

“{group_boundaries:[0,2620,2883],sample_boundaries:[0,40,80]}”

我想要

“{group_boundaries:[0-2620-2883],sample_boundaries:[0-40-80]}”

谢谢你

r regex gsub
1个回答
0
投票

基础 R 及其

gregexpr
:

vec <- "{group_boundaries:[0,2620,2883], sample_boundaries:[0,40,80]}"
gre <- gregexpr("(?<=\\[)[^]]+(?=\\])", vec, perl = TRUE)
regmatches(vec, gre)
# [[1]]
# [1] "0,2620,2883" "0,40,80"    
regmatches(vec, gre) |>
  lapply(gsub, pattern = ",", replacement = "-")
# [[1]]
# [1] "0-2620-2883" "0-40-80"    
regmatches(vec, gre) <- regmatches(vec, gre) |>
  lapply(gsub, pattern = ",", replacement = "-")
vec
# [1] "{group_boundaries:[0-2620-2883], sample_boundaries:[0-40-80]}"
© www.soinside.com 2019 - 2024. All rights reserved.