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.r98 chars4 lines
Output:
main.r17 chars2 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 underscoreIn 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