Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R-提取具有模式的单词,并用相反顺序的单词替换它们_R_Regex - Fatal编程技术网

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"