您可以使用
gsub("(?:\\G(?!^)|NOTE)\\K\\s", "@", a, perl=TRUE)
请看R demo.com/r/QQNbAV/2" rel="nofollow noreferrer">regex demo和R demo.
a <- "text text NOTE 3/1"
b <- "text NOTE 4.3%"
gsub("(?:\\G(?!^)|NOTE)\\K\\s", "@", a, perl=TRUE)
# => [1] "text text NOTE@@@@@@3/1"
gsub("(?:\\G(?!^)|NOTE)\\K\\s", "@", b, perl=TRUE)
# => [1] "text NOTE@@@4.3%"
Details:
(?:\G(?!^)|NOTE)
-上一次成功匹配的结束或NOTE
\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%"