Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.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 具有正向后看捕获组的gsub正则表达式_R_Regex - Fatal编程技术网

R 具有正向后看捕获组的gsub正则表达式

R 具有正向后看捕获组的gsub正则表达式,r,regex,R,Regex,我有如下字符串: "d1 x2 d2x4 5 specimens collected the smallest is 4 x 1 x 3 mm" " stomach x3 d2x4 8 pieces with the largest measuring 4 x 1 x 3 mm" 我想在“样本”一词前面的数字前加上一个句号,以便 "d1 x2 d2x4 .5 specimens collected the smallest is 4 x

我有如下字符串:

 "d1 x2 d2x4 5 specimens collected the smallest is 4 x 1 x 3 mm" 
 " stomach x3 d2x4 8 pieces with the largest measuring  4 x 1 x 3 mm"
我想在“样本”一词前面的数字前加上一个句号,以便

"d1 x2 d2x4 .5 specimens collected the smallest is 4 x 1 x 3 mm" 
" stomach x3 d2x4 .8 pieces with the largest measuring  4 x 1 x 3 mm"
我试过:

regstring<-"specimens|pieces"

gsub(paste0("(","(?<=\\d) ",regString,")"),"\\.\\1",inputString,perl=T)

如何在数字之前而不是之后获得句号?

您可以使用以下表达式:

(\d+)(\s+(?:specimens|pieces)\b)
并将其替换为

".\\1\\2"


R
中,这可能是

strings <- c("d1 x2 d2x4 5 specimens collected the smallest is 4 x 1 x 3 mm",
            " stomach x3 d2x4 8 pieces with the largest measuring  4 x 1 x 3 mm")
            
strings <- gsub("(\\d+)(\\s+(?:specimens|pieces)\\b)", ".\\1\\2", strings, perl = TRUE)
strings

strings我想我已经捕捉到了与下面的答案相似的信息:
sub(sprintf('\\b(\\d+\\s(%s))\\b',regstring),'.\\1',inputString)
。我把它复杂化了。感谢您在开始时甚至不需要
\b
。要将样本作为一个整体进行匹配,最好将
\b
移到末尾,即
(\d+)(\s+(?:样本|件)\b)
strings <- c("d1 x2 d2x4 5 specimens collected the smallest is 4 x 1 x 3 mm",
            " stomach x3 d2x4 8 pieces with the largest measuring  4 x 1 x 3 mm")
            
strings <- gsub("(\\d+)(\\s+(?:specimens|pieces)\\b)", ".\\1\\2", strings, perl = TRUE)
strings