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