How do I use gsub () to add a line to the beginning and remove a line from the end at the same time?

I want to match the end of a given string with a specific pattern. If the template exists, I want to remove it and add a specific line to the beginning of the given line.

For example: if I have gradesmeanA

a template as well meanA

, then I want to add "class A average" at the beginning gradesmeanA

and remove meanA

at the end. Thus, the result should be "middle class".

I want to use gsub()

regular expressions as well. I want to do it in one step.

What I have tried:

s1<-gsub(pattern="/\\w /meanA$",replacement="mean of class A / \\w/","gradesmeanA")

      

but doesn't work.

+3


source to share


1 answer


You can try the below code,

> s <- "gradesmeanA"
> sub("^(.*?)meanA$", "mean of class A \\1", s, perl=T)
[1] "mean of class A grades"
> sub("^(.*)meanA$", "mean of class A \\1", s)
[1] "mean of class A grades"

      

Sample Explanation:

  • ^

    Matches the beginning of the line.
  • ()

    Capture group commonly used for capturing characters.
  • (.*)meanA$

    all characters before the last line are meanA

    captured and the last one is meanA

    matched.
  • In sub or gsub, all matching characters must be replaced. In our case, all matching characters (the whole string) are replaced with mean of class A

    plus characters present inside the group index.
  • $

    Matches the end of the line.


OR

Ugly,

> gsub("^(.*?)(mean)(A)$", "\\2 of class \\3 \\1", s, perl=T)
[1] "mean of class A grades"

      

+8


source







All Articles