regex - Replace repeating character with another repeated character -
regex - Replace repeating character with another repeated character -
i replace 3 or more consecutive 0s in string consecutive 1s. example: '1001000001' becomes '1001111111'.
in r, wrote next code:
gsub("0{3,}","1",reporting_line_string)
but replaces 5 0s single 1. how can 5 1s ?
thanks,
you can utilize gsubfn
function, can supply replacement function replace content matched regex.
require(gsubfn) gsubfn("0{3,}", function (x) paste(replicate(nchar(x), "1"), collapse=""), input)
you can replace paste(replicate(nchar(x), "1"), collapse="")
stri_dup("1", nchar(x))
if have stringi
bundle installed.
or more concise solution, g. grothendieck suggested in comment:
gsubfn("0{3,}", ~ gsub(".", 1, x), input)
alternatively, can utilize next regex in perl mode replace:
gsub("(?!\\a)\\g0|(?=0{3,})0", "1", input, perl=true)
it extensible number of consecutive 0
changing 0{3,}
part.
i don't endorse utilize of solution, though, since less maintainable.
regex r
Comments
Post a Comment