您可以使用
gsub("(?:\\G(?!^)|^NOTE)\\K\\s", "@", a, perl=TRUE)
请参阅 regex demo 和 R demo。
a <- "NOTE 3/1"
b <- "NOTE 4.3%"
gsub("(?:\\G(?!^)|^NOTE)\\K\\s", "@", a, perl=TRUE)
# => [1] "NOTE@@@@@@3/1"
gsub("(?:\\G(?!^)|^NOTE)\\K\\s", "@", b, perl=TRUE)
# => [1] "NOTE@@@4.3%"
细节:
-
(?:\G(?!^)|^NOTE) - 上一次成功匹配的结尾或NOTE 在字符串的开头(如果它不总是在字符串的开头,只需删除^ 锚点,或使用\\b 匹配一个词的边界)
-
\K - 匹配重置运算符,丢弃到目前为止匹配的文本
-
\s - 一个空格字符。
这是一个stringr 版本(^ 为了更清晰而被删除),其中NOTE 之后匹配的空格在function(x) str_replace_all(x, "\\s", "@") 回调函数中分别替换为@ 字符:
library(stringr)
stringr::str_replace_all(a, "NOTE\\s+", function(x) str_replace_all(x, "\\s", "@"))
# => [1] "NOTE@@@@@@3/1"
stringr::str_replace_all(b, "NOTE\\s+", function(x) str_replace_all(x, "\\s", "@"))
# => [1] "NOTE@@@4.3%"