Bluish Coder

Programming Languages, Martials Arts and Computers. The Weblog of Chris Double.


2006-12-22

Search and Replace with Parser Combinators

I've added some code to the Factor parser combinator library to allow search and replace using parser combinators. The idea was to be able to do similar things with parser combinators that regular expressions are commonly used for. I've also started adding some simple reusable parsers for numbers, strings, etc.

The search word takes a string and a parser off the stack. It returns a sequence of all substrings in the original string that successfully parse by the parser. The result returned in the sequence is actually the result returned by the parser. For example:

"hello *world* from *factor*" 'bold' search . 
 => { "world" "factor" } 

"one 100 two 300" 'integer' search .
 => { 100 300 }

"one 100 two 300" 'integer' [ 2 * ] <@ search .
 => { 200 600 }

The search\* word takes a string and a sequence of parsers off the stack. It returns a sequence of all substrings in the original string that successfully parse by any of the parsers in the sequence. It is functionally the same as combining parsers with the <|> combinator.

"hello 123 \"world\" from 456 factor" 'string' 'integer' 2array search* . 
 => { 123 "world" 456 }

The replace word takes a string and parser off the stack. It returns the original string with all substrings that successfully parse by the parser replaced by the result of that parser.

"Hello *World*" 'bold' [ "&lt;strong>" swap "&lt;/strong>" 3append ] <@ replace .
 => "Hello &lt;strong>World&lt;/strong>"

The replace\* word takes a string and sequence of parsers off the stack. It does a fold, iterating through the sequence applying 'replace' using the parser and the results of the previous 'replace' call. The result is a string with all matching substrings from the parsers in the sequence being replaced by the results of those parsers.

"*Hello _World_*" 
  'bold' [ "&lt;strong>" swap "&lt;/strong>" 3append ] <@
  'italic' [ "&lt;emphasis>" swap "&lt;/emphasis>" 3append ] <@ 
  2array replace* .
 => "&lt;strong>Hello &lt;emphasis>World&lt;/emphasis>&lt;/strong>"

Tags


This site is accessable over tor as hidden service mh7mkfvezts5j6yu.onion, or Freenet using key:
USK@1ORdIvjL2H1bZblJcP8hu2LjjKtVB-rVzp8mLty~5N4,8hL85otZBbq0geDsSKkBK4sKESL2SrNVecFZz9NxGVQ,AQACAAE/bluishcoder/-44/


Tags

Archives
Links