提问人:Lucky sardar 提问时间:11/7/2023 更新时间:11/7/2023 访问量:37
R 查找并替换括号内的值 [duplicate]
R find and replace values inside brackets [duplicate]
问:
我想替换方括号内的字符串中的逗号,无法找到解决方案,我该如何使用 R 任何人请帮助我
“{group_boundaries:[0,2620,2883], sample_boundaries:[0,40,80]}”
我想要
“{group_boundaries:[0-2620-2883], sample_boundaries:[0-40-80]}”
谢谢
答:
2赞
r2evans
11/7/2023
#1
基础 R 及其:gregexpr
vec <- "{group_boundaries:[0,2620,2883], sample_boundaries:[0,40,80]}"
gre <- gregexpr("\\[[^]]+\\]", vec)
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]}"
正则表达式:
"\\[[^]]+\\]"
^^^ ^^^ the literal brackets, escaped since they are used for regex classes
^^^^^ one or more of anything other than the close bracket
评论
str
stringr::str_replace_all(str, "\\[[^\\]]*\\]", function(x) stringr::str_replace_all(x, ",", "-"))
vec
stringr::str_replace_all(vec, "\\[[^\\]]*\\]", function(x) stringr::str_replace_all(x, ",", "-"))