首页 > 解决方案 > R:如何用引号括起来字符串的每个元素

问题描述

我想从字符串中删除空格、句点和连字符,并用引号将结果字符串的每个元素括起来。此外,我想确保所有字母都是大写的。

我知道如何删除特殊字符列表,但由于我缺乏使用正则表达式或其他字符串操作函数(例如 stringr 函数)的经验,我无法添加封闭的引号。

如何转换字符串,例如

test1 <- "A.1, b-1, C"             # start string
test2 <- gsub("[ .-]", "", test1)  # remove period and hyphen

生成字符串'A1','B1','C'

标签: rregexgsubstringr

解决方案


在删除with并将大小写转换为大写之后,我们可以使用strspliton,后跟零个或多个空格.-gsub

strsplit(gsub("[.-]", "", toupper(test1)), ",\\s*")[[1]]
#[1] "A1" "B1" "C" 

如果我们需要单个字符串,在删除., and之后-,捕获单词 ( ) 并通过环绕捕获组的反向引用 ( ) 来\\w+替换它'\\1

gsub('(\\w+)', "'\\1'", gsub("[.-]+", "", toupper(test1)))
#[1] "'A1', 'B1', 'C'"

推荐阅读