[英]R - Extract words with a pattern and replace them with the words in inverse order
I have the following string vector of phrases. 我有以下短语的字符串向量。
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"
I want to replace de following pattern "apples \\\\d{1,4}"
by the reverse order of the found words, in each element of the vector. 我想在矢量的每个元素中按照找到的单词的相反顺序替换de以下模式"apples \\\\d{1,4}"
。
Any suggestions? 有什么建议?
We can do this with gsub
to capture words as a group ( \\\\w+
) followed by space and then capture the numbers as another group, replace it with the backreference in reverse order 我们可以用gsub
来捕获单词作为一个组( \\\\w+
),然后是空格,然后将数字作为另一个组捕获,用反向顺序替换它
gsub("(\\w+)\\s+(\\d+)", "\\2 \\1", x)
#[1] "I ate 100 apples already. No 50 apples uhmm" "He has 20 apples yeah"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.