gsub regex with positive lookbehind capture group

Viewed 56

I have strings such as:

 "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"

I'd like to add a full stop before the number directly in front of the word 'specimens' to get

"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"

I tried:

regstring<-"specimens|pieces"

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

which gives me:

[1] "d1 x2 d2x4 5. specimens collected the smallest is 4 x 1 x 3 mm mm"
[2] " stomach x3 d2x4 8 .pieces with the largest measuring  4 x 1 x 3 mm" 

How can I get the full stop before the number instead of after?

1 Answers

You may use the following expression instead:

(\d+)(\s+(?:specimens|pieces)\b)

And replace this with

".\\1\\2"

See a demo on regex101.com.


In R this could be

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

See a demo on ideone.com.

Related