Tom Wenseleers
Tom Wenseleers

Reputation: 7989

Regular expression in R to remove the part of a string after the last space

I would like to have a gsub expression in R to remove everything in a string that occurs after the last space. E.g. string="Da Silva UF" should return me "Da Silva". Any thoughts?

Upvotes: 4

Views: 1670

Answers (2)

hwnd
hwnd

Reputation: 70722

You can use the following.

string <- 'Da Silva UF'
gsub(' \\S*$', '', string)

[1] "Da Silva"

Explanation:

            ' '
\S*         non-whitespace (all but \n, \r, \t, \f, and " ") (0 or more times)
  $         before an optional \n, and the end of the string

Upvotes: 3

falsetru
falsetru

Reputation: 368954

Using $ anchor:

> string = "Da Silva UF"
> gsub(" [^ ]*$", "", string)
[1] "Da Silva"

Upvotes: 7

Related Questions