--- title: "Get started with zuregex" description: > Detect, extract, capture, replace and split with one web server log. output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Get started with zuregex} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>") ``` ```{r setup} library(zuregex) ``` We take a few lines of a web server's log and work through them: find the lines that match, pull out parts of them, turn them into a data frame, rewrite them and cut them up. After that you know the main `re_*()` functions and the rules they share. Moving from base R or stringr, limits on untrusted patterns and the C API each have their own article, listed at the end. ## Detect matches The log is a character vector. Its last element is not a log line, so we can see what a string that does not match gives. ```{r} log <- c( "2026-10-21 08:15:02 GET /index.html 200 512", "2026-10-21 08:15:09 POST /login 302 0", "2026-10-21 08:16:44 GET /missing 404 128", "not a log line" ) ``` Every function takes the strings first, as `x`, and then a **pattern**: a regular expression in PCRE2's syntax, which is the syntax of base R's `perl = TRUE`. `re_detect()` says which elements match. ```{r} re_detect(log, "GET") ``` One pattern is used for every element. The other choice is one pattern per element, as long as `x`. Here each line is tested for its own status code, and only the second line has the one asked for. ```{r} re_detect(log, c("404", "302", "200", "500")) ``` A pattern of any other length is an error: zuregex never recycles one. ## Extract matches `re_extract()` returns the text of the first match in each element, and `NA` where there is none. ```{r} re_extract(log, "/\\S+") ``` Parentheses in a pattern make a **group**, a part of the match you can ask for by itself. `group` picks one, by number or, for a group written `(?...)`, by name. This returns the status code alone, without the spaces the pattern needs around it. ```{r} re_extract(log, " (?\\d{3}) ", group = "status") ``` ## Capture groups as columns `re_match()` returns every group at once, as a data frame with one row per element. A named group gives its name to its column. ```{r} pattern <- "(?