Remove square brackets from a string vector

后端 未结 4 1855
逝去的感伤
逝去的感伤 2020-12-03 10:21

I have a character vector in which each element is enclosed in brackets. I want to remove the brackets and just have the string.

So I tried:

n = c(\"         


        
相关标签:
4条回答
  • 2020-12-03 10:38

    A regular expression substitution will do it. Look at the gsub() function.

    This gives you what you want (it removes any instance of '[' or ']'):

    gsub("\\[|\\]", "", n)
    
    0 讨论(0)
  • 2020-12-03 10:45

    You could gsub out the brackets like so:

    n = c("[Dave]", "[Tony]", "[Sara]")
    
    gsub("\\[|\\]", "", n)
    [1] "Dave" "Tony" "Sara"
    
    0 讨论(0)
  • 2020-12-03 10:45

    The other answers should be enough to get your desired output. I just wanted to provide a brief explanation of why what you tried didn't work.

    paste concatenates character strings. If you paste an empty character string, "", to something with a separator that is also an empty character string, you really haven't altered anything. So paste can't make a character string shorter; the result will either be the same (as in your example) or longer.

    0 讨论(0)
  • 2020-12-03 10:47

    If working within tidyverse:

    library(tidyverse); library(stringr)
    
    n = c("[Dave]", "[Tony]", "[Sara]")
    
    n %>% str_replace_all("\\[|\\]", "")
    [1] "Dave" "Tony" "Sara"
    
    0 讨论(0)
提交回复
热议问题