首页 > 解决方案 > 在条件后添加字符

问题描述

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, "\\.$", ".$")

谢谢!

标签: rregex

解决方案


有很多方法可以将 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$并将匹配替换为自身,与.,并$附加。

推荐阅读