Extract only characters after a space that comes after the last number in a string

Viewed 268

I'm not very good at using regex. I have a vector of strings. I would like to extract everything after the space following the last number. I've checked all sorts of other SO posts, but everything I've tried butchers the strings.

I've tried both directly extracting the text I want as well as extracting out the text I don't want. I've failed at both.

Here's a sample vector:

c("54 ABC, efg xyz", "ABC 08 abcdef ghijkl", "ABC 01-02 ghijkl")

Here's the desired output

c("ABC, efg xyz", "abcdef ghijkl", "ghijkl")

Here's what I've tried:

library(dplyr)
library(stringr)

c("54 ABC, efg xyz", "ABC 08 abcdef ghijkl", "ABC 01-02 ghijkl") %>% 
  str_replace("[^[:digit:]] +", "")
[1] "54 ABCefg xyz"      "AB08 abcdef ghijkl" "AB01-02 ghijkl"

And I tried breaking it up into steps:

c("54 ABC, efg xyz", "ABC 08 abcdef ghijkl", "ABC 01-02 ghijkl") %>% 
    str_replace_all("^[:digit:]+\\s", "") %>% 
    str_replace_all("ABC ", "") %>% 
    str_replace_all("^[:digit:]+\\s", "") %>% 
    str_replace_all(".*? ", "")
[1] "xyz"    "ghijkl" "ghijkl"

There were a few other attempts but not worth posting.

I'm sure someone will be able to solve this easily after my having spend a couple hours getting nowhere.

2 Answers

We can use sub to do this i..e match character (.*) till one or more digits (\\d+) followed by one or more space (\\s+) and replace with blank ("")

sub(".*\\d+\\s+", "", v1)

-output

[1] "ABC, efg xyz"  "abcdef ghijkl" "ghijkl"   

Or use str_remove

library(stringr)
str_remove(v1, ".*\\d+\\s+")
[1] "ABC, efg xyz"  "abcdef ghijkl" "ghijkl"  

data

v1 <- c("54 ABC, efg xyz", "ABC 08 abcdef ghijkl", "ABC 01-02 ghijkl")

I think you could also use the following solution:

library(stringr)

str_extract(vec, "(?<=\\s)([^0-9]+)")

[1] "ABC, efg xyz"  "abcdef ghijkl" "ghijkl" 
Related