-
Notifications
You must be signed in to change notification settings - Fork 1
/
searchreplace.tex
42 lines (29 loc) · 1.44 KB
/
searchreplace.tex
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
\chapter{Search and Replace with PEGs}\label{seachreplace}
The Parsing Expression Grammar library has code to allow search and replace using parsers. The idea was to be able to do similar things with parser combinators that regular expressions are commonly used for. The words are in the \texttt{peg.search} vocabulary.
\wordtable{
\vocabulary{peg.search}
\ordinaryword{search}{search ( string parser -- seq )}
}
The `search' word takes a string and a parser off the stack. It returns a sequence of all substrings in the original string that were successfully parsed by the parser. The result returned in the sequence is the AST produced by the parser. For example:
\begin{verbatim}
USING: peg peg.ebnf peg.parsers peg.search ;
: bold ( -- parser )
<EBNF rule="*" (!("*") .)+:s "*" => [[ s >string ]] EBNF> ;
"hello *world* from *factor*" bold search .
=> V{ "world" "factor" }
"one 100 two 300" integer-parser search .
=> V{ 100 300 }
"one 100 two 300" integer-parser [ 2 * ] action search .
=> V{ 200 600 }
\end{verbatim}
\wordtable{
\vocabulary{peg.search}
\ordinaryword{replace}{replace ( string parser -- result )}
}
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.
\begin{verbatim}
"Hello *World*" bold [
"<strong>" "</strong>" surround
] action replace .
=> "Hello <strong>World</strong>"
\end{verbatim}