Introduction
The stringr package provides consistent string handling functions. It's part of tidyverse.
String Detection
library(stringr)
text <- "Hello World"
# Detect pattern
str_detect(text, "World")
# Count matches
str_count(text, "l")
# Does it start/end?
str_starts(text, "Hello")
str_ends(text, "World")
String Extraction
# Extract first match
str_extract(text, "[A-Z][a-z]+")
# Extract all matches
str_extract_all(text, "[A-Z][a-z]+")
# Extract matched groups
str_match(text, "(He)(llo)")
String Replacement
# Replace first match
str_replace(text, "World", "R")
# Replace all matches
str_replace_all(text, "l", "L")
# Remove matches
str_remove(text, "l")
String Manipulation
str <- " Hello World "
str_trim(str) # Remove whitespace
str_squish(str) # Clean up whitespace
str_to_upper(str) # Uppercase
str_to_lower(str) # lowercase
str_pad(str, 20, side = "both") # Pad
Summary
stringr provides consistent string operations. Use these functions for clean, readable string code.