Elements of Regular Expressions
William A. Yarberry Jr. · Apress eBooks · 2021
Literals are simply characters themselves, such as “a” or “boat” or “123.” Some characters are “reserved” with special meanings, such as “+.” In the case of the plus sign, its special meaning is “additional characters like one just to the left of the + sign.” If you want to use any of these reserved characters as a literal in a regex, you need to escape them with a backslash. If you want to match 1+1=2, the correct regex is 1\\+1=2. Otherwise, the plus sign has a special meaning. Remember that two backslashes are required. string1 <- "This is elementary Watson. 1+1=2" my.regex <- "1\\+1=2" my.regex.replacement.value <- "two plus two equals four " sub(pattern = my.regex,replacement = my.regex.replacement.value,x = string1) ## [1] "This is elementary Watson. two plus two equals four "