英文:
Remove numbers and commas inside parenthesis (regex)
问题
我想提取这个测试向量中的数字。
我已经尝试过这个:
test <- c("(15, 80)","(100, 60)","(40, 40)","(30, 20)","(10, 60)")
stringr::str_extract(test, "[0-9:0-9:0-9], [0-9:0-9:0-9]")
但是返回相同的输入。我需要一个输出像这样:
"15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
英文:
I want to extract the numbers inside this test vector.
I've already tried this:
test <- c("(15, 80)","(100, 60)","(40, 40)","(30, 20)","(10, 60)")
stringr::str_extract(test, "[0-9:0-9:0-9], [0-9:0-9:0-9]")
But return the same input. I need an output like this:
"15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
答案1
得分: 2
Using a regex replacement approach with gsub()
we can try:
<!-- language: r -->
test <- c("(15, 80)","(100, 60)","(40, 40)","(30, 20)","(10, 60)")
output <- gsub("^\(|\)$", "", test)
output
[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
英文:
Using a regex replacement approach with gsub()
we can try:
<!-- language: r -->
test <- c("(15, 80)","(100, 60)","(40, 40)","(30, 20)","(10, 60)")
output <- gsub("^\\(|\\)$", "", test)
output
[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
答案2
得分: 2
trimws
可以在这种情况下工作。
trimws(test, whitespace = "[()]")
#[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
英文:
In this case trimws
would work.
trimws(test, whitespace = "[()]")
#[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
答案3
得分: 2
Using str_remove
library(stringr)
str_remove_all(test, "[()]")
[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
(Note: I've translated the code part as requested.)
英文:
Using str_remove
library(stringr)
str_remove_all(test, "[()]")
[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
答案4
得分: 1
你可以尝试使用 trimws
与 chartr
函数:
> trimws(chartr("()", " ", test))
[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
英文:
You can try trimws
along with chartr
> trimws(chartr("()", " ", test))
[1] "15, 80" "100, 60" "40, 40" "30, 20" "10, 60"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论