R-提取具有模式的单词,并用相反顺序的单词替换它们
我有下面的短语字符串向量R-提取具有模式的单词,并用相反顺序的单词替换它们,r,regex,R,Regex,我有下面的短语字符串向量 x <- c("I ate apples 100 already. No apples 50 uhmm" , "He has apples 20 yeah") 我想用向量的每个元素中找到的单词的相反顺序来替换de following模式“apples\\d{1,4}” 有什么建议吗 我们可以使用gsub将单词捕获为一个组(\\w+),后跟空格,然后将数字捕获为另一个组,以相反顺序替换为反向引用 gsub("(\\w+)\\s+(\\d+)", "\\2 \\1"
x <- c("I ate apples 100 already. No apples 50 uhmm" , "He has apples 20 yeah")
我想用向量的每个元素中找到的单词的相反顺序来替换de following模式“apples\\d{1,4}”
有什么建议吗 我们可以使用
gsub
将单词捕获为一个组(\\w+
),后跟空格,然后将数字捕获为另一个组,以相反顺序替换为反向引用
gsub("(\\w+)\\s+(\\d+)", "\\2 \\1", x)
#[1] "I ate 100 apples already. No 50 apples uhmm" "He has 20 apples yeah"
比我快+1
gsub("(\\w+)\\s+(\\d+)", "\\2 \\1", x)
#[1] "I ate 100 apples already. No 50 apples uhmm" "He has 20 apples yeah"