Replace a repeating character with another repeated character

I would like to replace 3 or more consecutive 0s in a string with consecutive 1s. Example: "1001000001" becomes "1001111111".

In R, I wrote the following code:

gsub("0{3,}","1",reporting_line_string)

but obviously it replaces 5 0 with one 1. How can I get 5 1s?

Thank,

+4
source share
4 answers

You can use a function gsubfnthat you can provide a replacement function to replace content that matches the regular expression.

require(gsubfn)
gsubfn("0{3,}", function (x) paste(replicate(nchar(x), "1"), collapse=""), input)

You can replace paste(replicate(nchar(x), "1"), collapse="")with stri_dup("1", nchar(x))if you have the package installed stringi.

Or a more concise solution, as G. Grothendieck in the comment:

gsubfn("0{3,}", ~ gsub(".", 1, x), input)

Perl :

gsub("(?!\\A)\\G0|(?=0{3,})0", "1", input, perl=TRUE)

0, 0{3,}.

, , .

+5

, , gregexpr regmatches. , , ...

x <- c("1001000001", "120000siw22000100")
x
# [1] "1001000001"        "120000siw22000100"
a <- regmatches(x, gregexpr("0{3,}", x))
regmatches(x, gregexpr("0{3,}", x)) <- lapply(a, function(x) gsub("0", "1", x))
x
# [1] "1001111111"        "121111siw22111100"
+2

For the regexignorant (like me) try brute force. Divide the string into separate characters with strsplit, find successive runs of "0" with rle, create a vector of the corresponding indices (run length "0"> 2) using rep, insert "1" into the indices, pasteon one line.

x2 <- strsplit(x = "1001000001", split = "")[[1]]
r <- rle(x2 == "0")
idx <- rep(x = r$lengths > 2, times = r$lengths)
x2[idx] <- "1"
paste(x2, collapse = "")
# [1] "1001111111"
+1
source
0(?=00)|(?<=00)0|(?<=0)0(?=0)

You can try this.Replace by. 1Watch the demo.

http://regex101.com/r/dP9rO4/5

0
source

All Articles