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

StackOverflow https://stackoverflow.com/questions/20497895

  •  31-08-2022
  •  | 
  •  

Вопрос

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?

Это было полезно?

Решение 2

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

Другие советы

Using $ anchor:

> string = "Da Silva UF"
> gsub(" [^ ]*$", "", string)
[1] "Da Silva"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top