字符串:从字符串中删除括号和括号

时间:2018-09-19 15:45:26

标签: r string stringr

我想从字符串中删除括号和括号。我得到了所需的结果,但是正在寻找更紧凑的方法。

Test <- c("-0.158)", "0.426)", "1.01)", "1.6)", "2.18)", "2.77]")

stringr::str_replace(
  string = Test
  , pattern = "\\)"
  , replacement = ""
)

# [1] "-0.158" "0.426"  "1.01"   "1.6"    "2.18"   "2.77]" 
stringr::str_replace(
    string = Test
  , pattern = "\\]"
  , replacement = ""
)

# [1] "-0.158)" "0.426)"  "1.01)"   "1.6)"    "2.18)"   "2.77"  
stringr::str_replace(
  string = stringr::str_replace(
            string = Test
            , pattern = "\\]"
            , replacement = ""
          )
  , pattern = "\\)"
  , replacement = ""
)

# [1] "-0.158" "0.426"  "1.01"   "1.6"    "2.18"   "2.77" 

想知道是否可以通过单个命令获得它

stringr::str_replace(
  string = Test
  , pattern = "\\)^]"
  , replacement = ""
)

已编辑

找到了一个非常简单的解决方案

readr::parse_number(Test) 
[1] -0.158 0.426 1.010 1.600 2.180 2.770.

1 个答案:

答案 0 :(得分:2)

我们可以使用|

gsub("\\)|\\]", "", Test)
#[1] "-0.158" "0.426"  "1.01"   "1.6"    "2.18"   "2.77"  

或者不要将括号放在[]

gsub("[][()]", "", Test)
#[1] "-0.158" "0.426"  "1.01"   "1.6"    "2.18"   "2.77"  

如果我们要提取数据而不是删除数据,请使用gregexpr/regmatches中的base Rstr_extract中的stringr来检查数字可以以{{ 1}},并包含-

.