r - R:如何用引号括起来字符串的每个元素
问题描述
我想从字符串中删除空格、句点和连字符,并用引号将结果字符串的每个元素括起来。此外,我想确保所有字母都是大写的。
我知道如何删除特殊字符列表,但由于我缺乏使用正则表达式或其他字符串操作函数(例如 stringr 函数)的经验,我无法添加封闭的引号。
如何转换字符串,例如
test1 <- "A.1, b-1, C" # start string
test2 <- gsub("[ .-]", "", test1) # remove period and hyphen
生成字符串'A1','B1','C'
?
解决方案
在删除with并将大小写转换为大写之后,我们可以使用strsplit
on,
后跟零个或多个空格.-
gsub
strsplit(gsub("[.-]", "", toupper(test1)), ",\\s*")[[1]]
#[1] "A1" "B1" "C"
如果我们需要单个字符串,在删除.
, and之后-
,捕获单词 ( ) 并通过环绕捕获组的反向引用 ( ) 来\\w+
替换它'
\\1
gsub('(\\w+)', "'\\1'", gsub("[.-]+", "", toupper(test1)))
#[1] "'A1', 'B1', 'C'"
推荐阅读
- spring-boot - MvcResult 的 getResponse().getContentAsString() 返回一个空数组
- reactjs - React-Bootstrap 模式仅显示和删除最后一个映射元素
- database - 我的 BigTable 架构会导致热点吗?
- mongodb - 带有卷的mongo docker如何指定logpath和dbpath?
- bash - Shell 脚本在作为 AWS SSM 命令的一部分运行时出错
- javascript - 存储 Angular 应用的动作映射
- blazor-server-side - 使用作为参数传递给页面的数据渲染组件
- c - 如何让 printf 显示计算机之前执行的计算?
- ios - 以日期格式快速获取过去 7 天和接下来 7 天
- python - 为什么我的 python 代码没有写入 MYSQL 数据库,使用实用程序代码文件