Abstract
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 "
Access this chapter
Tax calculation will be finalised at checkout
Purchases are for personal use only
Notes
- 1.
“Regular Expressions Quick Start,” accessed on March 23, 2020, www.regular-expressions.info/quickstart.html.
- 2.
“R: RegEx for Containing Pattern with Negation,” Stack Overflow, accessed on March 26, 2020, https://stackoverflow.com/questions/46898699/r-regex-for-containing-pattern-with-negation.
- 3.
“RegEx – Regular Expression Negation in R,” Stack Overflow, accessed on March 26, 2020, https://stackoverflow.com/questions/59139892/regular-expression-negation-in-r.
- 4.
“RegEx – Extract Capture Group Matches from Regular Expressions? (Or: Where Is Gregexec?),” Stack Overflow, accessed on March 26, 2020, https://stackoverflow.com/questions/18620571/extract-capture-group-matches-from-regular-expressions-or-where-is-gregexec.
- 5.
“R: Extract Matched Groups from a String,” accessed on March 26, 2020, https://jangorecki.gitlab.io/data.cube/library/stringr/html/str_match.html.
- 6.
“RegEx – Common Operators,” accessed on March 26, 2020, http://web.mit.edu/gnu/doc/html/regex_3.html.
- 7.
“RegEx Tutorial – Look ahead and Look behind Zero-Length Assertions,” accessed on March 16, 2020, www.regular-expressions.info/lookaround.html.
- 8.
“Regular Expressions,” accessed on March 17, 2020, https://stringr.tidyverse.org/articles/regular-expressions.html.
- 9.
“R: Regular Expressions as Used in R,” accessed on March 18, 2020, https://stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html.
Author information
Authors and Affiliations
Rights and permissions
Copyright information
© 2021 The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature
About this chapter
Cite this chapter
Yarberry, W. (2021). Elements of Regular Expressions. In: CRAN Recipes. Apress, Berkeley, CA. https://doi.org/10.1007/978-1-4842-6876-6_8
Download citation
DOI: https://doi.org/10.1007/978-1-4842-6876-6_8
Published:
Publisher Name: Apress, Berkeley, CA
Print ISBN: 978-1-4842-6875-9
Online ISBN: 978-1-4842-6876-6
eBook Packages: Professional and Applied ComputingApress Access BooksProfessional and Applied Computing (R0)