Let's assume you have both strings in one vector:
x = c("R is so tough for SAS programmer", "R why you so hard")
Then, if I understand your question correctly, you can use a combination of substr
to extract the first 7 characters of each string and then sub
to extract the part after the last space:
sub(".*\\s", "", substr(x, 1, 7))
#[1] "so" "y"
It may be safer to use
sub(".*\\s", "", trimws(substr(x, 1, 7), "right"))
which will cut off any whitespace on the right side of the vector resulting from substr
. This ensures that the sub
call won't accidentally match a space at the end of the string.