An alternative is:
exemplo <- c("Rua Pajé, 30, apto 44", "Av. Brasil,55, blocoB")
gsub("^([^,]+,[^,]+),.*$", "\\1", exemplo)
I use the markers ^
and $
, which are respectively the beginning and end of the string.
Then I use [^,]+
(one or more characters other than a comma), followed by a comma, followed by more characters than the comma. And I place all of this in parentheses to form a capture group.
Then we have the second comma, followed by .*
(zero or more characters), until the end of the string ($
).
In the substitution parameter I use \\1
, which corresponds to what was captured by the parentheses (in this case, everything before the second of the comma). Since it is the first pair of parentheses, then they correspond to the first capture group, hence the number 1
in "\\1"
. And since inside those parentheses is everything before the second comma, then \\1
is exactly the stretch you want. The result is:
[1] "Rua Pajé, 30" "Av. Brasil,55"
Watch it run on Ideone.com.