简体   繁体   中英

How to use gsub() to add a string to the front and remove a string from the end at same time?

I want to match end of given string to a certain pattern. If pattern is there, then I want to remove it and add a certain string to the front of given string.

Eg: If I have gradesmeanA and the pattern is meanA then I want to add "mean of class A " to the front of gradesmeanA and remove meanA at the end. So the result should be "mean of class A grades".

I want to use gsub() and regular expressions. I want to do this in one step.

What I tried:

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

but didn't work.

You could 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"

Pattern Explanation:

  • ^ Matches the start of a line.
  • () Capturing group usually used to capture characters.
  • (.*)meanA$ , all the characters before the last string meanA is captured and the last meanA is matched.
  • In sub or gsub, all the matched characters must be replaced. In our case, all the matched characters ( the whole line ) are replaced by mean of class A plus the chaarcters present inside the group index 1.
  • $ Matches the end of a line.

OR

An ugly one,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM