Matching and replacing patterns in R

I am not familiar with regexes at all and would like to match and replace patterns in R.

I would like to replace the template #1 , #2 in the vector: original = c("#1", "#2", "#10", "#11") with each vector value vec = c(1,2) .

As a result, I am looking for the following vector: c("1", "2", "#10", "#11") I'm not sure how to do this. I tried:

 for(i in 1:2) { pattern = paste("#", i, sep = "") original = gsub(pattern, vec[i], original, fixed = TRUE) } 

but I get:

 #> original #[1] "1" "2" "10" "11" 

instead: "1" "2" "#10" "#11"

I would be grateful for any help I can get! Thanks!

+6
source share
3 answers

Another option using gsubfn :

 library(gsubfn) gsubfn("^#([1-2])$", I, original) ## Function substituting [1] "1" "2" "#10" "#11" 

Or, if you want to explicitly use the values ​​of your vector using the vec values:

 gsubfn("^#[1-2]$", as.list(setNames(vec,c("#1", "#2"))), original) 

Or a formula notation equivalent to a function notation:

 gsubfn("^#([1-2])$", ~ x, original) ## formula substituting 
+3
source

Specify that you match the entire string from start ( ^ ) to end ( $ ).

Here I selected exactly the conditions that you are looking at in this example, but I assume that you need to expand it:

 > gsub("^#([1-2])$", "\\1", original) [1] "1" "2" "#10" "#11" 

So basically, β€œfrom the very beginning, look for a hash character followed by either the exact number one or two. One or two should be just one digit (so we are not using * or + or anything else), but also ends the line. Oh, and capture it one or two, because we want a back link.

+7
source

Here's a slightly different opinion, which uses a negative statement with zero width (what a sip!). This is (?!...) which matches # at the beginning of the line if what is in ... is not executed. In this case, two (or, which is the same thing, longer if they are adjacent) digits. It does not replace anything.

 gsub( "^#(?![0-9]{2})" , "" , original , perl = TRUE ) [1] "1" "2" "#10" "#11" 
+3
source

Source: https://habr.com/ru/post/958861/


All Articles