regex return string after underscore in r

To return the string after the underscore in R using regex, you can use the sub() function.

The pattern matching syntax for capturing the portion of the string after the underscore is "_+(.*)". This pattern matches one or more underscores and captures everything after it.

Here's an example code snippet to extract the string after the underscore from a given string:

# example string
my_string <- "hello_world"

# extract string after underscore
my_result <- sub("_+(.*)", "\\1", my_string)

# print the result
print(my_result)
161 chars
9 lines

Output:

main.r
[1] "world"
12 chars
2 lines

In the sub() function, the first argument is the pattern to match, the second argument is the replacement string, and the third argument is the input string.

We use \\1 in the replacement string to refer to the first capturing group (which is the (.*) part in our pattern). This tells the function to replace the entire string that matches the pattern with the captured string that follows the underscore.

In this case, the result is the string "world", which is everything after the underscore in the original string "hello_world".

gistlibby LogSnag