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

Regex match after last / and first underscore

Assuming I have the following string:

string = "path/stack/over_flow/Pedro_account"

I am intrested in matching the first 2 characters after the last / and before the first _. So in this case the desired out put is:

Pe

What I have so far is a mix of substr and str_extract:

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

substr(str_extract(string, "[^/]*$"),1,2)

which of course will give an answer but I belive there is a nice regex for it as well, and that is what I’m looking for.

>Solution :

You can use

library(stringr)
str_extract(string, "(?<=/)[^/]{2}(?=[^/]*$)")
## => [1] "Pe"

See the R demo and the regex demo. Details:

  • (?<=/) – a location immediately preceded with a / char
  • [^/]{2} – two chars other than /
  • (?=[^/]*$) – a location immediately preceded with zero or more chars other than / till the end of string.
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