how to substitue part of string

I am trying to remove the education word

x <-  c("sector_snapshot_eduction.png",   "sector_snapshot_eduction_qrc.png")
gsub("(sector_snapshot)(_.*)((?:qrc)?\\.png)", "\\1\\3", x)

Like this?

x <-  c("sector_snapshot_education.png",   "sector_snapshot_education_qrc.png")
gsub("_education", "", x)
[1] "sector_snapshot.png"     "sector_snapshot_qrc.png"

If you have different words...I want a general way

Please be more explicit why @FJCC 's solution was not what you want.

What if string is "sector_snapshot_transport.png"
"sector_snapshot_energy.png"

That is why I want a general case

I think you know what you mean.
I know I don't know what you mean.

1 Like
x <-  c("sector_snapshot_education.png",   "sector_snapshot_health_qrc.png",   "sector_snapshot_energy_qrc.png")

so i want to a general case of gsub instead of gsub("_education", "", x)

There is almost certainly a reasonably clean way to address this, but I'll be the next person to chime in that it is unclear what the complete replacement logic you are looking to achieve is. @HanOostdijk put it well: it is clear to you, but it is not being clearly communicated here.

You have only provided one true "before / after" example, and it's unclear from that one, along with your descriptions, as to what logic you are looking to apply. In your last example, for instance, are you looking to return sector_snapshot.png for both?

Perhaps a list of 5-10 "from -> to" examples might help the others on this thread understand what generalized pattern you are looking to apply.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.