Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R Regex expression with gsub

I am using gsub regex to select last part of expression

Example:

  • "Bla-text-01" – I want -> "text-01"
  • "Name-xpto-08" – I want -> "xpto-08"
  • "text-text-04" – I want -> "text-04"
  • "new-blaxpto-morexpto-07" – I want -> "morexpto-07"
  • "new-new-new-bla-ready-05" – I want -> "ready-05"

I created this code that works with first 3 cases but now I have a new request to also work with 5 cases.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

gsub(x = match$id,
          pattern =  "(.*?-)(.*)",
          replacement = "\\2")

Can you help me?

>Solution :

Try this regular expression:

sub(".*-(.*-.*)$", "\\1", x)
## [1] "text-01"     "xpto-08"     "text-04"     "morexpto-07" "ready-05"   

Other approaches would be:

# 2. use basename/dirname
xx <- gsub("-", "/", x)
paste(basename(dirname(xx)), basename(xx), sep = "-")
## [1] "text-01"     "xpto-08"     "text-04"     "morexpto-07" "ready-05"   

# 3. use scan
f <- function(x) {
  scan(text = x, what = "", sep = "-", quiet = TRUE) |>  
    tail(2) |>
    paste(collapse = "-")
}
sapply(x, f)
##              Bla-text-01             Name-xpto-08             text-text-04 
##                "text-01"                "xpto-08"                "text-04" 
##  new-blaxpto-morexpto-07 new-new-new-bla-ready-05 
##            "morexpto-07"               "ready-05" 

Note

Input in reproducible form:

x <- c("Bla-text-01", "Name-xpto-08", "text-text-04", "new-blaxpto-morexpto-07", 
"new-new-new-bla-ready-05")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading