I analyse text strings and I try replace all dots .
within round brackets ()
with commas ,
I found a regex that matches eveything within the brackets:
text <- "let's count (get . this . without dots) the days?"
brackets = "\\((.*?)\\)"
regmatches(text,regexpr(brackets,text))
gives me:
[1] "(get . this . without dots)"
As described here, I could use gsubfn
to do the changes:
library(gsubfn)
gsubfn(brackets, ~ gsub("\\.", ",",x), text)
gives me:
[1] "let's count get , this , without dots the days?"
instead of what I thought I would get:
[1] "let's count (get , this , without dots) the days?"
Why does gsubfn omit a part of my match? (i.e. the brackets)
Is there any other way the replace the .
within ()
with ,
You may keep as many capturing groups as you need in the original regex, no need to modify the pattern, just tell gsubfn
to use the whole match by passing backref=0
argument:
gsubfn("\\((.*?)\\)", ~ gsub("\\.", ",",x), text, backref=0)
[1] "let's count (get , this , without dots) the days?"