6

パッケージを使用stringrすると、ベクトル化された方法で正規表現の置換を簡単に実行できます。

質問: 次のことを行うにはどうすればよいですか。

のすべての単語を置き換えます

hello,world??your,make|[]world,hello,pos

数を増やすなど、さまざまな置換に

1,2??3,4|[]5,6,7

単純なセパレータは想定できないことに注意してください。実際の使用例はより複雑です。


stringr::str_replace_all動作しないようです

str_replace_all(x, "(\\w+)", 1:7)

すべての単語に適用される置換ごとにベクトルを生成するか、入力エントリが不確実または重複しているため、

str_replace_all(x, c("hello" = "1", "world" = "2", ...))

目的のために動作しません。

4

3 に答える 3

3

このようなものには「鉱石」パッケージをお勧めします。特に注目すべきはore.searchandore.substで、後者は置換値として関数を受け入れることができます。

例:

library(ore)

x <- "hello,world??your,make|[]world,hello,pos"

## Match all and replace with the sequence in which they are found
ore.subst("(\\w+)", function(i) seq_along(i), x, all = TRUE)
# [1] "1,2??3,4|[]5,6,7"

## Create a cool ore object with details about what was extracted
ore.search("(\\w+)", x, all = TRUE)
#   match: hello world  your make   world hello pos
# context:      ,     ??    ,    |[]     ,     ,   
#  number: 1==== 2====  3=== 4===   5==== 6==== 7==
于 2015-05-02T06:34:44.890 に答える
1

ここにベースRソリューションがあります。また、ベクトル化する必要があります。

x="hello,world??your,make|[]world,hello,pos"
#split x into single chars
x_split=strsplit(x,"")[[1]]
#find all char positions and replace them with "a"
x_split[gregexpr("\\w", x)[[1]]]="a"
#find all runs of "a"
rle_res=rle(x_split)
#replace run lengths by 1
rle_res$lengths[rle_res$values=="a"]=1
#replace run values by increasing number
rle_res$values[rle_res$values=="a"]=1:sum(rle_res$values=="a")
#use inverse.rle on the modified rle object and collapse string
paste0(inverse.rle(rle_res),collapse="")

#[1] "1,2??3,4|[]5,6,7"
于 2015-05-02T15:53:03.487 に答える