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 extract string matching pattern and before space

I am really new to R and having a hard time understanding what the syntax means when trying to extract or gsub the part of a string that I want
My data looks as follows

d <- "Para | YTX-456 | XYZ-123456 | NTX-897"

I would like to extract "XYZ-123456", so the three specific letters, the "-" and any number that follows up to but without the space. Everything I tried so far just extracts the numbers with the space. How can I find a match for "XYZ-" in the string and extract it along with all the numbers that follow?

Thanks!

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

>Solution :

You can use stringr::str_extract() here, with [0-9]+ identifying all numbers after the desired "XYZ-" pattern:

stringr::str_extract(d,"XYZ-[0-9]+")

# [1] "XYZ-123456"
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