regex return string after the last underscore in r

To extract the substring after the last underscore from a string in R, we can use regular expressions with the sub() function. The following code demonstrates how to do this:

main.r
string <- "some_text_after_last_underscore"
result <- sub(".*_(.*)", "\\1", string)
print(result)
98 chars
4 lines

Output:

main.r
[1] "underscore"
17 chars
2 lines

In the regular expression ".*_(.*)":

  • .* matches any character (except newline), zero or more times
  • _ matches the last underscore in the string
  • (.*) matches and captures any character after the last underscore

In the replacement string "\\1":

  • \\1 substitutes the captured group in the regular expression (i.e., the substring after the last underscore)

The sub() function applies the regular expression to the input string and returns the replacement string with the last substring after the underscore.

gistlibby LogSnag