R - 用模式提取单词并将其替换为反向顺序的单词

时间:2017-12-06 16:40:53

标签: r regex

我有以下短语的字符串向量。

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

我希望结果是:

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

我希望在矢量的每个元素中按照找到的单词的相反顺序替换模式"apples \\d{1,4}"之后的de。

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

我们可以使用const AppContainer = ReactRedux.connect( state => ({ appState: state.appReducer.appState }), mapDispatchToProps, }) )(App); 执行此操作以将单词(gsub)作为一组(\\w+)后跟空格捕获,然后将数字捕获为另一个组,将其替换为反向顺序的反向引用

gsub("(\\w+)\\s+(\\d+)", "\\2 \\1", x)
#[1] "I ate 100 apples already. No 50 apples uhmm" "He has 20 apples yeah"