Regular Expressions in Racket

Racket offers built-in support for regular expressions. Here are some examples of common regexp-related tasks in Racket.

#lang racket

(require racket/string)

; This tests whether a pattern matches a string.
(define match (regexp-match? #rx"p([a-z]+)ch" "peach"))
(displayln match)

; Above we used a string pattern directly, but for
; other regexp tasks you'll need to use a compiled
; regexp for better performance.
(define r (pregexp "p([a-z]+)ch"))

; Many functions are available for regexps. Here's
; a match test like we saw earlier.
(displayln (regexp-match? r "peach"))

; This finds the match for the regexp.
(displayln (regexp-match r "peach punch"))

; This also finds the first match but returns the
; start and end indexes for the match instead of the
; matching text.
(displayln (format "idx: ~a" (regexp-match-positions r "peach punch")))

; The regexp-match function includes information about
; both the whole-pattern matches and the submatches
; within those matches. For example this will return
; information for both p([a-z]+)ch and ([a-z]+).
(displayln (regexp-match r "peach punch"))

; The All variants of these functions apply to all
; matches in the input, not just the first. For
; example to find all matches for a regexp.
(displayln (regexp-match* r "peach punch pinch"))

; Providing a non-negative integer as the second
; argument to these functions will limit the number
; of matches.
(displayln (take (regexp-match* r "peach punch pinch") 2))

; Our examples above had string arguments. We can also 
; provide byte strings as arguments.
(displayln (regexp-match? r #"peach"))

; When creating global variables with regular
; expressions you can use the regexp or pregexp
; functions. They will raise an exception if the
; pattern is invalid.
(define r2 (pregexp "p([a-z]+)ch"))
(displayln (format "regexp: ~a" r2))

; The regexp package can also be used to replace
; subsets of strings with other values.
(displayln (regexp-replace r "a peach" "<fruit>"))

; The regexp-replace* function allows you to transform 
; all matches in a string.
(define (to-upper bs)
  (string-upcase (bytes->string/utf-8 bs)))

(displayln (regexp-replace* r #"a peach punch" to-upper))

Running this program would produce output similar to:

#t
#t
(peach ea)
idx: ((0 . 5))
(peach ea)
(peach punch pinch)
(peach punch)
#t
regexp: #px"p([a-z]+)ch"
a <fruit>
a PEACH PUNCH

For a complete reference on Racket regular expressions, check the Racket documentation on regexps.