ZetCode

R stringr

last modified November 19, 2026

The stringr package gives string operations a consistent interface. Every function starts with str_, takes the string as its first argument, and takes the pattern as its second, so there is no need to remember which base function puts the pattern first. The functions are vectorised: a character vector goes in, a vector of the same length comes out. Patterns are regular expressions unless a literal match is requested with fixed(). This article covers the verbs for length, case, whitespace, detection, extraction, replacement, splitting, joining, and sorting, and finishes by parsing a list of contact records. The examples use stringr 1.6.0 with R 4.5.2.

The examples need the stringr package, which is not part of base R. Install it once with install.packages("stringr"); the installing packages section of the introduction explains the details.

Length, case, and whitespace

str_length counts the characters in each string, including spaces. str_to_upper, str_to_lower, and str_to_title change the case, while str_trim removes whitespace from both ends and str_squish also collapses runs of spaces inside the string into one.

verbs.R
library(stringr)
people <- c("  Ada   Lovelace ", "Grace Hopper", "Alan Turing")
print(str_length(people))
print(str_to_upper(people))
print(str_to_lower(people))
print(str_trim(people))
print(str_squish(people))
print(str_to_title("ada lovelace"))
cat("longest:", max(str_length(people)), "\n")

The first string has seventeen characters because it carries two leading spaces, a run of three spaces inside, and one trailing space. Trimming removes only the ends and leaves the internal run, which is why the trimmed string still measures fourteen characters. Squishing produces the clean name in twelve. str_to_title capitalises the first letter of every word, which is convenient for names but should not be applied to text that already has its own capitalisation.

$ Rscript verbs.R
[1] 17 12 11
[1] "  ADA   LOVELACE " "GRACE HOPPER"      "ALAN TURING"      
[1] "  ada   lovelace " "grace hopper"      "alan turing"      
[1] "Ada   Lovelace" "Grace Hopper"   "Alan Turing"   
[1] "Ada Lovelace" "Grace Hopper" "Alan Turing" 
[1] "Ada Lovelace"
longest: 17 

Detecting patterns

str_detect returns one logical value per string, which makes it usable directly as a filter. str_starts and str_ends test the two ends, str_subset keeps the matching strings, str_which returns their positions, and str_count counts the matches in each string. All of them are case-sensitive by default.

detect.R
library(stringr)
people <- c("Ada Lovelace", "Grace Hopper", "Alan Turing", "Edsger Dijkstra")
print(str_detect(people, "a"))
print(str_starts(people, "A"))
print(str_ends(people, "e"))
print(str_subset(people, "o"))
print(str_which(people, "T"))
print(str_count(people, "a"))

Every name contains a lowercase a, but only two start with a capital A. str_subset keeps the two names that contain an o, and str_which finds the capital T at position three. The counts are 2, 1, 1, and 1: Ada has an a at the end and another in Lovelace, Grace has one, and the capital A in Alan is not counted because the pattern is lowercase. Passing ignore_case = TRUE would change that last result.

$ Rscript detect.R
[1] TRUE TRUE TRUE TRUE
[1]  TRUE FALSE  TRUE FALSE
[1]  TRUE FALSE FALSE FALSE
[1] "Ada Lovelace" "Grace Hopper"
[1] 3
[1] 2 1 1 1

Extracting by position

str_sub cuts a substring by position. The start and end are inclusive, and a negative position counts from the end of the string, so -3 means the last three characters. When only the start is given, the substring runs to the end. The assignment form of the function replaces the selected range in place.

substrings.R
library(stringr)
people <- c("Ada Lovelace", "Grace Hopper", "Alan Turing")
print(str_sub(people, 1, 3))
print(str_sub(people, -3))
print(str_sub(people, 5))
words <- c("ada", "grace", "alan")
str_sub(words, 1, 1) <- str_to_upper(str_sub(words, 1, 1))
print(words)

The first three characters of each name give Ada, Gra, and Ala. The last three characters give the endings ace, per, and ing, and starting at position five keeps the surname together with the space that precedes it. The assignment replaces the first letter of each lowercase word with its uppercase form, which turns ada, grace, and alan into proper names. Position-based extraction needs no pattern, which makes it the safer choice for fixed-width identifiers.

$ Rscript substrings.R
[1] "Ada" "Gra" "Ala"
[1] "ace" "per" "ing"
[1] "Lovelace" "e Hopper" " Turing" 
[1] "Ada"   "Grace" "Alan" 

Replacing text

str_replace changes the first match in each string and str_replace_all changes every match. The pattern is a regular expression, so a dot stands for any character. Wrapping the pattern in fixed turns off the regular expression engine and matches the literal text instead.

replacing.R
library(stringr)
text <- c("the cat sat", "the dog sat", "the bird sat")
print(str_replace(text, "sat", "stood"))
print(str_replace_all(text, "the", "a"))
print(str_replace("a.b", ".", "-"))
print(str_replace("a.b", fixed("."), "-"))

The first call replaces sat with stood once per string, and the second replaces the with a everywhere. The third call is the trap: the pattern dot matches the first character, so the result is -.b rather than a-b. The fourth call uses fixed(".") and produces the intended result. Replacement is vectorised over the strings, the patterns, and the replacements.

$ Rscript replacing.R
[1] "the cat stood"  "the dog stood"  "the bird stood"
[1] "a cat sat"  "a dog sat"  "a bird sat"
[1] "-.b"
[1] "a-b"

Extracting with patterns

str_extract returns the first match in each string and str_extract_all returns every match as a list, because the number of matches can differ from string to string. The pattern \\d{4} means four digits, and [A-Z][a-z]+ means a capital letter followed by one or more lowercase letters.

extract.R
library(stringr)
text <- c("Ada 1815", "Grace 1906", "Alan 1912")
print(str_extract(text, "\\d{4}"))
print(str_extract(text, "[A-Z][a-z]+"))
print(str_extract_all("a1 b22 c333", "\\d+"))

The four-digit pattern picks the birth year from every record. The second pattern picks the first capitalised word, which is the first name because the surname also starts with a capital but occurs later. The list returned by str_extract_all has one element holding 1, 22, and 333, the three runs of digits in the input. The backslash is doubled inside an R string because the string parser consumes the first one.

$ Rscript extract.R
[1] "1815" "1906" "1912"
[1] "Ada"   "Grace" "Alan" 
[[1]]
[1] "1"   "22"  "333"

Capture groups

Parentheses in a pattern create capture groups, and str_match returns them as columns of a matrix. The first column is the whole match and the following columns are the groups in order. This is the shortest way to split a structured record without writing a loop over regexec.

capture.R
library(stringr)
records <- c("Ada Lovelace <ada@example.com>",
             "Grace Hopper <grace@example.com>")
m <- str_match(records, "(\\w+) (\\w+) <(.+)>")
print(m)
print(m[, 2])
print(m[, 4])

The pattern reads a first word, a space, a second word, a space, and an email address inside angle brackets. The matrix has two rows and four columns: the full match, the first name, the last name, and the address. Extracting columns two and four gives the names and the addresses without any further parsing. A group that does not participate in the match becomes NA, which keeps the matrix rectangular.

$ Rscript capture.R
     [,1]                               [,2]    [,3]       [,4]               
[1,] "Ada Lovelace <ada@example.com>"   "Ada"   "Lovelace" "ada@example.com"  
[2,] "Grace Hopper <grace@example.com>" "Grace" "Hopper"   "grace@example.com"
[1] "Ada"   "Grace"
[1] "ada@example.com"   "grace@example.com"

Splitting and joining

str_split divides each string at a pattern and returns a list, because the pieces can have different lengths. str_split_fixed takes a maximum number of pieces and returns a matrix instead. str_c joins strings with a separator, and str_glue interpolates R expressions written inside braces.

split-join.R
library(stringr)
people <- c("Ada Lovelace", "Grace Hopper")
print(str_split(people, " "))
print(str_split_fixed(people, " ", 2))
print(str_c("Hello", people, sep = ", "))
print(str_glue("Hello {people}"))

The list from str_split has one element per person, each holding a first and a last name. The fixed version returns the same values as a two-column matrix. str_c pairs the greeting with each name because both arguments have the same length, and str_glue produces one line per name without a separator argument. The glue result is a character vector with a class that prints the lines directly.

$ Rscript split-join.R
[[1]]
[1] "Ada"      "Lovelace"

[[2]]
[1] "Grace"  "Hopper"

     [,1]    [,2]      
[1,] "Ada"   "Lovelace"
[2,] "Grace" "Hopper"  
[1] "Hello, Ada Lovelace" "Hello, Grace Hopper"
Hello Ada Lovelace
Hello Grace Hopper

Sorting, padding, and truncating

str_sort orders strings with the Unicode collation rules of the current locale, and str_order returns the positions instead. str_pad adds characters to a fixed width, and str_trunc shortens a string to a width and marks the cut with an ellipsis.

sort-pad.R
library(stringr)
words <- c("banana", "apple", "Cherry")
print(str_sort(words))
print(str_order(words))
print(str_sort(words, decreasing = TRUE))
print(str_pad(c("a", "bb"), width = 4, side = "left"))
print(str_trunc("abcdefgh", width = 5))

The sort follows the collation rules of the locale, so Cherry lands between apple and banana rather than before both of them. The order vector 2, 1, 3 records the positions of the sorted words in the input. Padding with side = "left" right-aligns the short strings, and truncating to width five keeps two characters and adds three dots, because the ellipsis counts toward the width. The base functions sort and substr do similar work with different defaults.

$ Rscript sort-pad.R
[1] "apple"  "banana" "Cherry"
[1] 2 1 3
[1] "Cherry" "banana" "apple" 
[1] "   a" "  bb"
[1] "ab..."

A complete example

The final script parses three contact records. It captures the first name, the last name, and the email in one pass, splits each address at the at sign, and checks the addresses against a simple pattern. The result is a small table of names and address parts without a single explicit loop.

report.R
library(stringr)
records <- c(
  "Ada Lovelace <ada@example.com>",
  "Grace Hopper <grace@example.com>",
  "Alan Turing <alan@example.com>"
)
parts <- str_match(records, "^(\\w+) (\\w+) <(.+)>$")
first <- parts[, 2]
last <- parts[, 3]
email <- parts[, 4]
address <- str_split_fixed(email, "@", 2)
print(str_c(first, last, sep = " "))
print(address)
cat("valid:", all(str_detect(email, "^[a-z]+@[a-z]+\\.[a-z]+$")), "\n")

The captured names come back as a character vector, and the addresses split into a three-row matrix with the user name in the first column and the domain in the second. The validation pattern requires lowercase letters before the at sign and a dot in the domain, and all three addresses satisfy it. The anchors ^ and $ make the check cover the whole string; without them, a partial match would also pass.

$ Rscript report.R
[1] "Ada Lovelace" "Grace Hopper" "Alan Turing" 
     [,1]    [,2]         
[1,] "ada"   "example.com"
[2,] "grace" "example.com"
[3,] "alan"  "example.com"
valid: TRUE 

Next steps

The strings article covers the base R functions behind these verbs, and the regular expressions article explains the pattern syntax used throughout this one. The dplyr article shows how str_detect fits into a table pipeline through filter, and the tidyr article separates columns with patterns rather than positions.

Source

stringr package documentation

stringr reference: string length and case

stringr reference: detect matches

stringr reference: substring by position

stringr reference: replace matches

stringr reference: extract matches

stringr reference: split and join strings

In this article we have measured and recased strings, trimmed and squished whitespace, and detected patterns with logical predicates. We extracted substrings by position, replaced the first or every match, and pulled values out with regular expressions and capture groups. We split strings into lists and matrices, joined them with str_c and str_glue, sorted and padded them, and parsed a set of contact records. The series continues with R hypothesis testing.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.