R - 使用模式提取单词并用相反顺序的单词替换它们

3

我有一个短语字符串向量,如下所示。

x <- c("I ate apples 100 already. No apples 50 uhmm" , "He has apples 20 yeah")

And I expect the result to be:

"I ate 100 apples already. No 50 apples uhmm" , "He has 20 apples yeah"

我希望能够在向量的每个元素中将以下模式"apples \\d{1,4}"替换为找到的单词的反向顺序。 有什么建议吗?
1个回答

3
我们可以使用来捕获单词()并将其作为一组,然后紧跟空格并捕获数字作为另一组,最后按照相反的顺序替换回溯引用。
gsub("(\\w+)\\s+(\\d+)", "\\2 \\1", x)
#[1] "I ate 100 apples already. No 50 apples uhmm" "He has 20 apples yeah"   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接