1
10
100
1000
10000
1e+05
Lecture 11
As you have likely noticed, the individual characters in a string (element of a character vector) cannot be directly accessed. The base language provides a number helper functions for pattern matching and manipulation of these objects:
paste()
, paste0()
- concatenate strings
substr()
, substring()
- extract or replace substrings
sprintf()
- C-like string construction
nchar()
- counts characters
strsplit()
- split a string into substrings
grep()
, grepl()
- regular expression pattern matching
sub()
, gsub()
- regular expression pattern replacement
+
many more - the See Also section of the the above functions’ documentation to find additional functions.
str_pad()
formatC()
(base)str_trim()
,str_squish()
str_trunc()
x = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
[1] "Lorem ipsum dolor sit amet, consectetur adipiscing elit, ..."
[1] "...in culpa qui officia deserunt mollit anim id est laborum."
[1] "Lorem ipsum dolor sit amet, c... mollit anim id est laborum."
str_wrap()
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
[1] "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\nincididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis\nnostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu\nfugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in\nculpa qui officia deserunt mollit anim id est laborum."
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
str_glue()
This is a simplified wrapper around glue::glue()
(use the original for additional control).
[1] "lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
[1] "LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT, SED DO EIUSMOD TEMPOR INCIDIDUNT UT LABORE ET DOLORE MAGNA ALIQUA."
[1] "Lorem Ipsum Dolor Sit Amet, Consectetur Adipiscing Elit, Sed Do Eiusmod Tempor Incididunt Ut Labore Et Dolore Magna Aliqua."
[1] "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
Function | Description |
---|---|
str_detect |
Detect the presence or absence of a pattern in a string. |
str_locate |
Locate the first position of a pattern and return a matrix with start and end. |
str_extract |
Extracts text corresponding to the first match. |
str_match |
Extracts capture groups formed by () from the first match. |
str_split |
Splits string into pieces and returns a list of character vectors. |
str_replace |
Replaces the first matched pattern and returns a character vector. |
str_remove |
Removes the first matched pattern and returns a character vector. |
str_view |
Show the matches made by a pattern. |
Many of these functions have variants with an _all
suffix (e.g. str_replace_all
) which will match more than one occurrence of the pattern in a string.
An escape character is a character which results in an alternative interpretation of the subsequent character(s).
These vary from language to language but for most string implementations \
is the escape character which is modified by a single following character.
Some common examples:
Literal | Character |
---|---|
\' |
single quote |
\" |
double quote |
\\ |
backslash |
\n |
new line |
\r |
carriage return |
\t |
tab |
\b |
backspace |
\f |
form feed |
As of v4.0, R has the ability to define raw character sequences which avoids the need for most escape characters, they can be constructed using the r"(...)"
syntax, where ...
is the raw string.
The power of regular expressions comes from their ability to use special metacharacters to modify how pattern matching is performed.
Because of their special properties they cannot be matched directly, if you need to match one you need to escape it first (precede it by \
).
The problem is that regex escapes live on top of character escapes, so we need to use two levels of escapes.
To match | Regex | Literal | Raw |
---|---|---|---|
. |
\. |
"\\." |
r"(\.)" |
? |
\? |
"\\?" |
r"(\?)" |
! |
\! |
"\\!" |
r"(\!)" |
## Error: '\[' is an unrecognized escape in character string starting ""\["
How do we detect if a string contains a \
character?
Sometimes we want to specify that our pattern occurs at a particular location in a string, we indicate this using anchor metacharacters.
Regex | Anchor |
---|---|
^ or \A |
Start of string |
$ or \Z |
End of string |
\b |
Word boundary |
\B |
Not word boundary |
If there are more than one pattern we would like to match we can use the or (|
) metacharacter.
When we want to match whole classes of characters at a time there are a number of convenience patterns built in,
Meta Char | Class | Description |
---|---|---|
. |
Any character except new line (\n ) |
|
\s |
[:space:] |
White space |
\S |
Not white space | |
\d |
[:digit:] |
Digit (0-9) |
\D |
Not digit | |
\w |
Word (A-Z, a-z, 0-9, or _) | |
\W |
Not word | |
[:punct:] |
Punctionation |
How would we write a regular expression to match a telephone number with the form (###) ###-####
?
## Error: '\d' is an unrecognized escape in character string starting ""(\d"
We can also specify our own classes using square brackets
Class | Type |
---|---|
[abc] |
Class (a or b or c) |
[^abc] |
Negated class (not a or b or c) |
[a-c] |
Range lower case letter from a to c |
[A-C] |
Range upper case letter from A to C |
[0-7] |
Digit between 0 to 7 |
For the following vector of randomly generated names, write a regular expression that,
detects if the person’s first name starts with a vowel (a,e,i,o,u)
detects if the person’s last name starts with a vowel
detects if either the person’s first or last name start with a vowel
detects if neither the person’s first nor last name start with a vowel
c("Jeremy Cruz", "Nathaniel Le", "Jasmine Chu", "Bradley Calderon Raygoza",
"Quinten Weller", "Katelien Kanamu-Hauanio", "Zuhriyaa al-Amen",
"Travale York", "Alexis Ahmed", "David Alcocer", "Jairo Martinez",
"Dwone Gallegos", "Amanda Sherwood", "Hadiyya el-Eid", "Shaimaaa al-Can",
"Sarah Love", "Shelby Villano", "Sundus al-Hashmi", "Dyani Loving",
"Shanelle Douglas")
05:00
Attached to literals or character classes these allow a match to repeat some number of time.
Quantifier | Description |
---|---|
* |
Match 0 or more |
+ |
Match 1 or more |
? |
Match 0 or 1 |
{3} |
Match Exactly 3 |
{3,} |
Match 3 or more |
{3,5} |
Match 3, 4 or 5 |
How would we improve our previous regular expression for matching a telephone number with the form (###) ###-####
?
What went wrong here?
Groups allow you to connect pieces of a regular expression for modification or capture.
Group | Description |
---|---|
(a | b) | match literal “a” or “b” , group either |
a(bc)? | match “a” or “abc” , group bc or nothing |
(abc)def(hig) | match “abcdefhig” , group abc and hig |
(?:abc) | match “abc” , non-capturing group |
Validating an email address:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"
(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")
@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[
(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:
(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Write a regular expression that will extract all phone numbers contained in the vector above.
Once that works use groups to extracts the area code separately from the rest of the phone number.
05:00
Sta 523 - Fall 2023