summaryrefslogtreecommitdiff
path: root/bs/re.scm
blob: 46cfa9e677d174d0277d1c65755559c3a85fcc32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
(library (bs re)

  ;; Similar to Python's `re` module. One big difference is that the
  ;; string object to be searched is always the first argument to a
  ;; function. This allows us to pipe a string through multiple
  ;; transformations. For example:
  ;;
  ;; (-> " string "
  ;;     string.strip
  ;;     (re.search "in")
  ;;     (re.group 1))
  ;;
  ;; TODO: consider putting the string as the last argument, to fit with
  ;; other container types like `list`, then use ->>
  ;; TODO: port srfi-115 to guile
  ;; TODO: make `match` and `search` do different things

  (export match group sub search compile
          EXTENDED
          ;; I IGNORECASE M MULTILINE
          )
  (import (rnrs base)
          ;; TODO: port to srfi-115
          (ice-9 regex))

  ;; (define I regexp/icase)
  ;; (define IGNORECASE regexp/icase)
  ;; (define M regexp/newline)
  ;; (define MULTILINE regexp/newline)
  (define EXTENDED 'regexp/extended)

  (define (compile pattern . flags)
    "Compile `pattern` into a regular expression object."
    (apply make-regexp (cons pattern flags)))


  (define (match string pattern)
    "If zero or more characters at the beginning of `string` match the regular
expression `pattern`, return a corresponding match object."
    (regexp-exec pattern string))

  (define (group match-obj n)
    (if match-obj
        (match:substring match-obj n)
        #f))

  (define (sub string pattern repl)
    "Return the string obtained by replacing the leftmost non-overlapping
occurrences of `pattern` in `string` by the replacement `repl`. If the pattern
isn’t found, string is returned unchanged."
    (regexp-replace pattern string repl))

  (define (search string pattern)
    "Scan through `string` looking for the first location where the regular
expression `pattern` produces a match, and return a corresponding match
object. Returns `#f` if no match is found."
    (string-match pattern string)))