typestar

stringr with groups in R

Capture groups, named or numbered, extracted into a matrix or a tibble.

library(stringr)
library(tibble)

lines <- c("INFO serve: started", "WARN db: slow query", "nonsense")
pattern <- "^(\\w+) (\\w+): (.*)$"

matches <- str_match(lines, pattern)
print(matches)
print(as_tibble(matches[, -1], .name_repair = ~ c("level", "logger", "msg")))

print(str_count(lines, "\\w+"))
print(str_locate(lines, "serve"))
print(str_detect("Typestar", regex("typestar", ignore_case = TRUE)))

How it works

  1. str_match returns the whole match then each group.
  2. regex() carries options like case insensitivity.
  3. str_count and str_locate answer the other questions.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
404
Tokens
101
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 3 of 3 in stringr, step 7 of 10 in Functional & text tools.

← Previous Next →