regex after underscore in r

To regex after underscore in R, you can use the sub or gsub function to match and replace patterns in a string.

Here's an example to extract the substring after the last underscore in a string:

# sample data
text <- "this_is_a_sample_text"

# use sub() function to remove everything before and including the last underscore
result <- sub("^.+_", "", text)

# output
print(result)
# "text"
195 chars
10 lines

The regular expression ^.+_ matches everything before and including the last underscore. The sub function then replaces this matched pattern with an empty string, effectively removing it from the original string.

If you want to keep the part before the underscore, you can use the strsplit function to split the string into two parts:

# use strsplit() function to split the string by underscore
parts <- strsplit(text, "_")

# extract the last part after the underscore
result <- parts[[1]][length(parts[[1]])]

# output
print(result)
# "text"
209 chars
10 lines

gistlibby LogSnag