# Sample string
text <- "This is a sample string"
# Use gsub to remove everything before the last whitespace
# The regular expression `.*\\s` matches any character (.) any number of times (*)
# followed by a whitespace character (\\s), as many times as possible
# up to the last whitespace due to the greedy nature of `.*`
# The replacement is an empty string, effectively removing the match
result <- gsub(".*\\s", "", text)
# Print the result
print(result)
## [1] "string"
# Sample text
text <- "This, is a sample, string with, several, commas"
# Use gsub to remove everything before the last comma (including the comma itself)
# The regular expression `.*\\,` is used:
# `.*` - matches any character (except for line terminators) as many times as possible
# `\\,` - matches the character `,` literally (escaped comma)
# The `.*` is greedy and will match as much as it can, including commas, until the last comma is reached
result <- gsub(".*\\, ", "", text)
# Print the result
print(result)
## [1] "commas"
#####################################
# Sample text
text <- "This is a sample, string with, several, commas."
# Use gsub to remove everything after the last comma (including the comma itself)
# The regular expression `\\,[^,]*$` is explained as follows:
# `\\,` - matches the character `,` literally
# `[^,]*` - matches any character except a comma, zero or more times
# `$` - asserts position at the end of a line
# This pattern finds the last comma and everything after it until the end of the string
result <- gsub("\\,[^,]*$", "", text)
# Print the result
print(result)
## [1] "This is a sample, string with, several"