r - 在条件后添加字符
问题描述
stringg <- c("You are\ngoing to learn 3 things, the first one is not to extract, and\n2 and 3 are simply digits.", "....", "....",....)
在 R Studio 中,我想找到所有以“。”结尾的列表项/字符串。在点之后我想添加一个 $ 符号。
grep("\\.$", stringg , value = TRUE) # this gives me the string from list which ends with a dot
我可以使用哪个命令添加 $?
我知道我可以像下面一样使用 str_replace 但我想知道是否可以添加而不是替换它?
str_replace(stringg, "\\.$", ".$")
谢谢!
解决方案
有很多方法可以将 char 添加到以特定字符结尾的字符串中。
以下是 R 正则表达式函数中使用的主要三个正则表达式引擎的一些:
stringg <- c("You are\ngoing to learn 3 things, the first one is not to extract, and\n2 and 3 are simply digits.", "....", "....")
sub("(\\.)$", "\\1$", stringg)
sub("$(?<=\\.)", "$", stringg, perl=TRUE)
library(stringr)
str_replace(stringg, "\\.$", "\\0$")
在线查看R 演示。
细节
sub("(\\.)$", "\\1$", stringg)
- TRE 正则表达式:(\.)
将文字点捕获到 ID 为 1 的捕获组中,然后$
断言字符串末尾的位置,然后将匹配项(点)替换为存储在组 1 中的相同值(请参阅\1
反向引用) 然后$
添加 a。sub("$(?<=\\.)", "$", stringg, perl=TRUE)
- PCRE 正则表达式:匹配字符串的结尾,$
然后检查是否有一个点紧靠在当前位置的左侧,借助(?<=\.)
正向向后看,然后将位置替换为$
,即$
只是附加到末尾细绳str_replace(stringg, "\\.$", "\\0$")
- ICU 正则表达式:在这里,它与上面的 TRE 正则表达式的示例几乎相同,但不需要捕获整个消费模式(点),因为stringr
函数支持第零个反向引用,即引用整个匹配值的那个. 因此,.
字符串末尾的 与\.$
模式匹配,\0$
并将匹配替换为自身,与.
,并$
附加。
推荐阅读
- typescript - 打字稿:ES6 Map + 索引签名 = 没有错误?
- python - Python重试打开文件
- android - 没有加号的新资源 ID 声明
- sql - 对 postgresql 表中的值求和并平衡记录
- chef-infra - 未找到 Chef 自定义资源属性
- python-3.x - 图包含一个循环
- mysql - 导致 MySQL 最大密钥长度超出的 Spring 数据
- node.js - 如何在 Angular 2 中应用 LDAP?
- java - 无法使用 jcifs 连接到 unc 位置
- sql - 如何为显示的 azure cosmos db 文档编写 SQL 查询?