R: removing numbers at begin and end of a string

后端 未结 3 1805
小鲜肉
小鲜肉 2020-12-19 09:56

I\'ve got the following vector:

words <- c(\"5lang\",\"kasverschil2\",\"b2b\")

I want to remove \"5\" in \"5lang\"

3条回答
  •  被撕碎了的回忆
    2020-12-19 10:27

    You can use gsub which uses regular expressions:

    gsub("^[0-9]|[0-9]$", "", words)
    # [1] "lang"        "kasverschil" "b2b"
    

    Explanation:

    The pattern ^[0-9] matches any number at the beginning of a string, while the pattern [0-9]$ matches any number at the end of the string. by separating these two patterns by | you want to match either the first or the second pattern. Then, you replace the matched pattern with an empty string.

提交回复
热议问题