ZetCode

Scheme regular expressions

last modified November 25, 2026 Guile 3.0

A regular expression is a pattern that describes a set of strings, such as "one or more digits" or "a word followed by a colon". Programs use regular expressions to search text, extract parts of it, check its format, and replace pieces of it. GNU Guile provides them in the (ice-9 regex) module, which uses the POSIX extended regular expressions of the C library. This article covers the module with GNU Guile 3.0.7; the strings article shows the simpler searches with string-contains and string-index.

Searching for a pattern

string-match searches a string for the first match of a pattern. It returns a match structure, or #f when there is no match. match:substring extracts the matched text.

search.scm
(use-modules (ice-9 regex))

(define m (string-match "[0-9]+" "Order 66 was shipped on day 12."))
(display (match:substring m))
(newline)

(define (first-number text)
  (let ((m (string-match "[0-9]+" text)))
    (if m
        (match:substring m)
        "no number")))

(display (first-number "Room 101"))
(newline)
(display (first-number "no digits here"))
(newline)

The pattern [0-9]+ means one or more digits, so the first search finds 66. A match structure is only available when the search succeeds, so code must check for #f before using it. first-number does that with if and returns a replacement text when the string has no digits.

$ guile search.scm
66
101
no number

Match positions

A match structure also records where the match lies. match:start and match:end return the indexes of the first character and the character after the match, and match:prefix and match:suffix return the text before and after it.

positions.scm
(use-modules (ice-9 regex))

(define text "Order 66 was shipped on day 12.")

(define m (string-match "[0-9]+" text))
(display (list (match:start m) (match:end m)))
(newline)
(write (match:prefix m))
(newline)
(write (match:suffix m))
(newline)

(define next (string-match "[0-9]+" text (match:end m)))
(display (match:substring next))
(display " at ")
(display (match:start next))
(newline)

The digits 66 occupy indexes 6 and 7, so the end index is 8. string-match accepts a start index as its third argument. Starting the search at the end of the first match finds the next number, 12 at index 28. Indexes count characters, not bytes, so they work with substring also for text with accented letters.

$ guile positions.scm
(6 8)
"Order "
" was shipped on day 12."
12 at 28

The pattern language

Most characters in a pattern match themselves. The special characters build larger patterns: ?, *, and + repeat the preceding item zero or one, zero or more, and one or more times, and {3} exactly three times. Brackets list allowed characters, . matches any character, | separates alternatives, and ^ and $ anchor the pattern at the start and end of the string.

patterns.scm
(use-modules (ice-9 regex))

(define (test pattern . texts)
  (display pattern)
  (newline)
  (for-each (lambda (text)
              (let ((m (string-match pattern text)))
                (display "  ")
                (write text)
                (display " -> ")
                (write (and m (match:substring m)))
                (newline)))
            texts))

(test "colou?r" "color" "colour" "colr")
(test "ab+c" "ac" "abc" "abbbc")
(test "^[A-Z][a-z]*" "Prague" "new York")
(test "[[:digit:]]{3}-[[:digit:]]{4}" "call 555-0199 now" "55-019")
(test "cat|dog" "hot dog" "category")
(test "\\.txt$" "notes.txt" "notes.txt.bak")
(test "[[:alpha:]]+" "12 žltá ruža")

test applies a pattern to several strings and writes the matched part, or #f. Without anchors, a pattern may match anywhere, so cat|dog finds cat inside category. POSIX patterns have no \d or \w; character classes such as [[:digit:]], [[:alpha:]], and [[:space:]] take their place. [[:alpha:]] follows the locale and matches accented letters, while [a-z] would miss ž. A backslash makes a special character literal, and inside a Scheme string it has to be written twice: "\\.txt$" is the pattern \.txt$.

$ guile patterns.scm
colou?r
  "color" -> "color"
  "colour" -> "colour"
  "colr" -> #f
ab+c
  "ac" -> #f
  "abc" -> "abc"
  "abbbc" -> "abbbc"
^[A-Z][a-z]*
  "Prague" -> "Prague"
  "new York" -> #f
[[:digit:]]{3}-[[:digit:]]{4}
  "call 555-0199 now" -> "555-0199"
  "55-019" -> #f
cat|dog
  "hot dog" -> "dog"
  "category" -> "cat"
\.txt$
  "notes.txt" -> ".txt"
  "notes.txt.bak" -> #f
[[:alpha:]]+
  "12 žltá ruža" -> "žltá"

Groups

Parentheses group part of a pattern, so a quantifier can apply to the whole group, and they also capture the text that the group matched. (match:substring m n) returns the text of group n, counted by the opening parentheses from the left; group 0 is the whole match.

groups.scm
(use-modules (ice-9 regex))

(define date-pattern "([0-9]{4})-([0-9]{2})-([0-9]{2})")

(define (parse-date text)
  (let ((m (string-match date-pattern text)))
    (and m
         (map (lambda (n) (string->number (match:substring m n)))
              '(1 2 3)))))

(display (parse-date "released on 2026-11-25"))
(newline)
(display (parse-date "released yesterday"))
(newline)

(define version "([a-z]+)(-([0-9]+))?")

(define (show-version text)
  (let ((m (string-match version text)))
    (display (match:count m))
    (display " ")
    (write (list (match:substring m 1) (match:substring m 3)))
    (newline)))

(show-version "guile-3")
(show-version "guile")

parse-date captures the year, month, and day of an ISO date and converts them to numbers. The version pattern has an optional group (-([0-9]+))? with a nested group for the number. match:count returns the number of groups plus one for the whole match, here 4. A group that did not take part in the match returns #f.

$ guile groups.scm
(2026 11 25)
#f
4 ("guile" "3")
4 ("guile" #f)

Compiled patterns and flags

string-match compiles the pattern on every call. make-regexp compiles it once into a regular expression object, and regexp-exec applies it to a string. make-regexp also accepts flags; regexp/icase ignores case.

compiled.scm
(use-modules (ice-9 regex))

(define problem (make-regexp "^(error|warning): *" regexp/icase))

(define lines
  '("ERROR: disk full"
    "info: backup started"
    "Warning:   low memory"
    "error: timeout"
    "note: error: in the middle"))

(for-each (lambda (line)
            (let ((m (regexp-exec problem line)))
              (when m
                (display (string-downcase (match:substring m 1)))
                (display " | ")
                (display (match:suffix m))
                (newline))))
          lines)

(display (regexp? problem))
(newline)

The pattern finds lines that start with error or warning in any case, followed by a colon and optional spaces. The program prints the kind in lower case and the rest of the line, which match:suffix returns without the spaces. The last line contains error:, but not at the start, so ^ rejects it. regexp? tests for a compiled pattern.

$ guile compiled.scm
error | disk full
warning | low memory
error | timeout
#t

Every match

list-matches returns a list of all non-overlapping matches, and fold-matches combines them into a single value like fold does with a list.

every.scm
(use-modules (ice-9 regex))

(define text "Order 66 was shipped on day 12, box 7 of 150.")

(define numbers
  (map match:substring (list-matches "[0-9]+" text)))
(display numbers)
(newline)

(define total
  (fold-matches "[0-9]+" text 0
                (lambda (m sum)
                  (+ sum (string->number (match:substring m))))))
(display total)
(newline)

(define (word-count text)
  (length (list-matches "[[:alpha:]]+" text)))

(display (word-count "Hello there, how are you?"))
(newline)

Mapping match:substring over the matches gives the four numbers of the text as strings. fold-matches adds them up without building a list first; the procedure receives a match and the result so far. word-count counts runs of letters, so the comma and the question mark do not disturb it.

$ guile every.scm
(66 12 7 150)
235
5

Replacing text

regexp-substitute/global replaces every match. Its first argument is a port, or #f to return a string. The items after the pattern and the string describe the output for each match: 'pre is the text before the match, 'post the rest, a string is inserted as it is, a number inserts a group, and a procedure receives the match and returns the text to insert.

replace.scm
(use-modules (ice-9 regex))

(define (squeeze text)
  (regexp-substitute/global #f " +" text 'pre " " 'post))

(display (squeeze "too    many   spaces  here"))
(newline)

(define (european-dates text)
  (regexp-substitute/global #f "([0-9]{4})-([0-9]{2})-([0-9]{2})" text
                            'pre 3 "." 2 "." 1 'post))

(display (european-dates "from 2026-11-25 to 2026-12-01"))
(newline)

(define (double-prices text)
  (regexp-substitute/global
   #f "[0-9]+" text
   'pre
   (lambda (m)
     (number->string (* 2 (string->number (match:substring m)))))
   'post))

(display (double-prices "tea 3, cake 12, coffee 4"))
(newline)

squeeze replaces each run of spaces with a single space. european-dates writes the captured groups of each date in reverse order with dots between them. double-prices computes the replacement with a procedure. The final 'post is what makes the substitution global: it continues the search in the rest of the string.

$ guile replace.scm
too many spaces here
from 25.11.2026 to 01.12.2026
tea 6, cake 24, coffee 8

Validating a whole string

To check the format of a value, the pattern must match the whole string, not just a part of it. Text that comes from the user must also be quoted before it becomes part of a pattern, and a pattern built at run time may be invalid.

validate.scm
(use-modules (ice-9 regex) (ice-9 exceptions))

(define (whole-match? pattern text)
  (and (string-match (string-append "^(" pattern ")$") text) #t))

(define product-code "[A-Z]{2}-[0-9]{4}")

(for-each (lambda (code)
            (display code)
            (display (if (whole-match? product-code code) " valid" " invalid"))
            (newline))
          '("AB-1234" "AB-12345" "xAB-1234" "ab-1234"))

(define price "$4.50")
(display (string-match price "costs $4.50 now"))
(newline)
(display (regexp-quote price))
(newline)
(display (match:start (string-match (regexp-quote price) "costs $4.50 now")))
(newline)

(guard (e ((error? e)
           (display "bad pattern: ")
           (display (exception-message e))
           (newline)))
  (string-match "([0-9]+" "x 42"))

whole-match? wraps the pattern in ^( and )$; the group makes the anchors apply to all alternatives of a pattern with |. and turns the match into #t. The text $4.50 used as a pattern finds nothing, because $ is an anchor and . matches any character. regexp-quote escapes the special characters, and the quoted pattern finds the price. An invalid pattern raises an error of kind regular-expression-syntax, whose message comes from the C library.

$ guile validate.scm
AB-1234 valid
AB-12345 invalid
xAB-1234 invalid
ab-1234 invalid
#f
\$4\.50
6
bad pattern: Unmatched ( or \(

Parsing a log file

A common use of regular expressions is reading structured text such as the access log of a web server. Each line holds a client address, a time, a request, a status code, and a size.

logs.scm
(use-modules (ice-9 regex) (ice-9 rdelim) (ice-9 format)
             (srfi srfi-1) (srfi srfi-9))

(define-record-type <request>
  (make-request ip method path status size)
  request?
  (ip request-ip) (method request-method) (path request-path)
  (status request-status) (size request-size))

(define log-entry
  (make-regexp
   "^([0-9.]+) [^[]*\\[[^]]*\\] \"([A-Z]+) ([^ ]+) [^\"]*\" ([0-9]{3}) ([0-9]+)$"))

(define (parse-line line)
  (let ((m (regexp-exec log-entry line)))
    (and m
         (make-request (match:substring m 1)
                       (match:substring m 2)
                       (match:substring m 3)
                       (string->number (match:substring m 4))
                       (string->number (match:substring m 5))))))

(define (read-requests port)
  (let loop ((line (read-line port)) (acc '()))
    (cond ((eof-object? line) (reverse acc))
          ((parse-line line)
           => (lambda (request) (loop (read-line port) (cons request acc))))
          (else
           (format #t "skipped: ~a~%" line)
           (loop (read-line port) acc)))))

(define (count-status request counts)
  (let ((pair (assv (request-status request) counts)))
    (if pair
        (begin (set-cdr! pair (+ (cdr pair) 1)) counts)
        (append counts (list (cons (request-status request) 1))))))

(define requests (call-with-input-file "access.log" read-requests))

(for-each (lambda (r)
            (when (>= (request-status r) 400)
              (format #t "~d ~a ~a from ~a~%" (request-status r)
                      (request-method r) (request-path r) (request-ip r))))
          requests)

(format #t "~d requests, ~d bytes~%"
        (length requests) (apply + (map request-size requests)))
(for-each (lambda (pair)
            (format #t "status ~a: ~d~%" (car pair) (cdr pair)))
          (fold count-status '() requests))

The pattern has five groups: the address, the method, the path, the status, and the size. In the pattern, [^[]* skips everything up to the opening bracket, \[[^]]*\] skips the bracketed time, and [^"]* the rest of the quoted request; in the Scheme string, the backslashes are doubled and the quotes escaped. parse-line turns a matching line into a record and returns #f for any other line, which read-requests reports and skips. The program then lists the failed requests, the totals, and the number of requests per status code, counted with fold into an association list.

$ cat access.log
192.168.1.10 - - [25/Nov/2026:10:01:12 +0100] "GET /index.html HTTP/1.1" 200 5120
192.168.1.11 - - [25/Nov/2026:10:01:15 +0100] "GET /scheme/ HTTP/1.1" 200 8400
192.168.1.10 - - [25/Nov/2026:10:02:03 +0100] "GET /favicon.ico HTTP/1.1" 404 512
10.0.0.5 - - [25/Nov/2026:10:03:41 +0100] "POST /login HTTP/1.1" 302 0
192.168.1.12 - - [25/Nov/2026:10:04:00 +0100] "GET /scheme/regular-expressions/ HTTP/1.1" 200 21300
this line is broken
10.0.0.5 - - [25/Nov/2026:10:05:19 +0100] "GET /admin HTTP/1.1" 403 256
192.168.1.11 - - [25/Nov/2026:10:06:27 +0100] "GET /old-page HTTP/1.1" 404 512
$ guile logs.scm
skipped: this line is broken
404 GET /favicon.ico from 192.168.1.10
403 GET /admin from 10.0.0.5
404 GET /old-page from 192.168.1.11
7 requests, 36100 bytes
status 200: 3
status 404: 2
status 302: 1
status 403: 1

Source

Regular Expressions — GNU Guile Reference Manual

Regular Expressions — POSIX.1-2024

In this article we have searched strings with string-match, read match positions, used the POSIX pattern language and groups, compiled patterns with flags, collected and folded every match, replaced text, validated whole strings, quoted user text, handled invalid patterns, and parsed a web server log. The files article covers reading the log line by line, and the records article the record type that holds a request.

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 Scheme tutorials.