Kun*_*Ren 6 regex r stringr stringi
使用stringr包,很容易以矢量化方式执行正则表达式替换.
问题:如何执行以下操作:
替换中的每个单词
hello,world??your,make|[]world,hello,pos
Run Code Online (Sandbox Code Playgroud)
不同的替代品,例如增加数量
1,2??3,4|[]5,6,7
Run Code Online (Sandbox Code Playgroud)
注意,不能假设简单的分隔符,实际用例更复杂.
stringr::str_replace_all 似乎没有用,因为它
str_replace_all(x, "(\\w+)", 1:7)
Run Code Online (Sandbox Code Playgroud)
为应用于所有单词的每个替换生成一个向量,或者它具有不确定和/或重复的输入条目,以便
str_replace_all(x, c("hello" = "1", "world" = "2", ...))
Run Code Online (Sandbox Code Playgroud)
不会为此目的而工作.
这是另一个想法gsubfn.该pre函数在替换之前运行,并且fun为每个替换运行函数:
library(gsubfn)
x <- "hello,world??your,make|[]world,hello,pos"
p <- proto(pre = function(t) t$v <- 0, # replace all matches by 0
fun = function(t, x) t$v <- v + 1) # increment 1
gsubfn("\\w+", p, x)
Run Code Online (Sandbox Code Playgroud)
这使:
[1] "1,2??3,4|[]5,6,7"
Run Code Online (Sandbox Code Playgroud)
这种变化会给出相同的答案,因为gsubfn维护了一个count用于proto函数的变量:
pp <- proto(fun = function(...) count)
gsubfn("\\w+", pp, x)
Run Code Online (Sandbox Code Playgroud)
有关使用的示例,请参阅gsubfn插图count.