简体   繁体   中英

stringr: Removing Parentheses and Brackets from string

I want to remove parentheses and brackets from a string. I got the required result, however looking for more compact method.

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" 

Wonder if it can be obtained with a single command something like this

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

Edited

Found a very simple solution

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

We can use |

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

or instead of escaping place the brackets inside the []

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

If we want to do the extract instead of removing use either gregexpr/regmatches from base R or str_extract from stringr to check for patterns where a number could start with - and include .

library(stringr)
str_extract(Test, "-?[0-9.]+")
#[1] "-0.158" "0.426"  "1.01"   "1.6"    "2.18"   "2.77"  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM