user8042238
user8042238

Reputation: 45

How to remove string before last specific symbol

Say I have a string like this

"Delete:Delete:Delete:Keep"

How do do I clean this so that only "Keep" remains. Furthermore, how can I apply this to an entire column.

I want to keep the string after the final colon, there can be from 1 to 4 colons in a single cell

Thanks

Upvotes: 0

Views: 192

Answers (3)

Andre Elrico
Andre Elrico

Reputation: 11480

alternatively,

x = "Delete:Delete:Delete:Keep"

sub(".*:(?=[^:]+$)", "", x, perl = TRUE)

or

sub(".*?(?=[^:]+$)", "", x, perl = TRUE)

regex concepts:

lazy quantifier, positive lookahead

Upvotes: 1

Julius Vainora
Julius Vainora

Reputation: 48201

You may use

sub(".*:(.*)", "\\1", "Delete:Delete:Delete:Keep")
# [1] "Keep"

and similarly for a column:

df$col <- sub(".*:(.*)", "\\1", df$col)

Here's how it works: .* matches everything before the last : because of greedy matching. Then (.*) captures everything after the last :, which is that becomes our final value.

Upvotes: 2

YOLO
YOLO

Reputation: 21709

You can also use strsplit

# d is your column
d <- c("Delete:Delete:Delete:Keep","Delete:Delete:Delete:Keep","Delete:Delete:Delete:Keep")

sapply(d, function(x) tail(unlist(strsplit(x, ":")), 1), USE.NAMES = F)
[1] "Keep" "Keep" "Keep"

Upvotes: 1

Related Questions