6. Pattern Matching

Introduction

# PicoLisp has no strings, and doesn't operate on symbol names directly.
# (see the "Strings" section). Instead, patterns are applied to lists.
#-----------------------------
(match Pattern List)
(fill Pattern [Symbol|List])
#-----------------------------
: (match '(@Name had a @Adj lamb) '(Mary had a little lamb))
-> T
: @Name
-> (Mary)
: @Adj
-> (little)
#-----------------------------

Copying and Substituting Simultaneously

#-----------------------------
: (replace '(here in this town) 'this 'that 'town 'village)
-> (here in that village)
#-----------------------------
# strip to basename
: (let F (chop "abc/def/ghi")
   (prinl (last (split F '/)))  # Using 'split'
   (prinl (stem F '/)) )        # or 'stem'
ghi
ghi
#-----------------------------
# Make All Words Title-Cased
: (mapcar
      '((W) (pack (uppc (car W)) (cdr W)))
      (split (chop "Mary had a little lamb") " ") )
-> ("Mary" "Had" "A" "Little" "Lamb")
#-----------------------------
: (glue '/
   (replace
      (split (chop "/usr/man/man3/foo.1") "/")
      '("m" "a" "n" "3")
      '("c" "a" "t" "3") ) )
-> "/usr/man/cat3/foo.1"
#-----------------------------
: (mapcar
   '((S) (pack (glue '/ (head -1 (split (chop S) '/))) "/lib"))
   '("/usr/bin" "/bin" "/usr/local/bin") )
-> ("/usr/lib" "/lib" "/usr/local/lib")
#-----------------------------

Matching Letters

#-----------------------------
(not
   (find
      '((C) (nor (>= "Z" C "A") (>= "z" C "a")))
      List ) )  # it is purely alphabetic
#-----------------------------

Matching Words

#-----------------------------
# as many non-whitespace bytes as possible
: (make (find '((C) (or (sp? C) (nil (link C)))) (chop "abcd efg")))
-> ("a" "b" "c" "d")

# as many letters, apostrophes, and hyphens
: (make
   (find
      '((C)
         (nand
            (or (>= "Z" C "A") (>= "z" C "a") (sub? C "`-"))
            (link C) ) )
      (chop "ab`c-d/e") ) )
-> ("a" "b" "`" "c" "-" "d")
#-----------------------------

# ...

#-----------------------------

Commenting Regular Expressions

Finding the Nth Occurrence of a Match

Matching Multiple Lines

Reading Records with a Pattern Separator

Extracting a Range of Lines

Matching Shell Globs as Regular Expressions

Speeding Up Interpolated Matches

Testing for a Valid Pattern

Honoring Locale Settings in Regular Expressions

Approximate Matching

Matching from Where the Last Pattern Left Off

Greedy and Non-Greedy Matches

Detecting Duplicate Words

Expressing AND, OR, and NOT in a Single Pattern

Matching Multiple-Byte Characters

Matching a Valid Mail Address

Matching Abbreviations

Program: urlify

Program: tcgrep

Regular Expression Grabbag