Debian Codegraph @

easel/esl_regexp.tex

raw
1
2 The regexp module contains portable functions for using regular
3 expressions to match and parse strings.
4
5 There are many different regular expression syntaxes. Easel
6 implements a small regular expression machine with a limited syntax,
7 allowing the most familiar and important regular expression
8 operators. It takes advantage of a compact, public domain regular
9 expression engine written by Henry Spencer at the University of
10 Toronto. Easel's regular expressions are not as powerful as the
11 regular expression syntax in the Perl language, for example, but are
12 sufficient for many useful parsing needs in a C application.
13
14 \subsection{The regexp API}
15
16 The module implements one object: a regular expression matching
17 ``machine'', \ccode{ESL\_REGEXP}.
18
19 The API defines ten functions:
20
21 \begin{tabular}{ll}
22 \multicolumn{2}{c}{\textbf{creating/destroying a regexp machine}}\\
23 \ccode{esl\_regexp\_Create()} & Creates a new \ccode{ESL\_REGEXP}. \\
24 \ccode{esl\_regexp\_Destroy()} & Destroys a created \ccode{ESL\_REGEXP}.\\
25 \ccode{esl\_regexp\_Inflate()} & Inflates an allocated \ccode{ESL\_REGEXP} shell. \\
26 \ccode{esl\_regexp\_Deflate()} & Deflates an inflated \ccode{ESL\_REGEXP} shell. \\
27 \multicolumn{2}{c}{\textbf{matching a pattern against a string}}\\
28 \ccode{esl\_regexp\_Match()} & Finds first match of a pattern in a string.\\
29 \ccode{esl\_regexp\_Compile()} & Precompile a pattern, for \ccode{\_MultipleMatches()}.\\
30 \ccode{esl\_regexp\_MultipleMatches()} & Finds next match of a compiled pattern in a string.\\
31 \multicolumn{2}{c}{\textbf{retrieving (sub)match information}}\\
32 \ccode{esl\_regexp\_SubmatchDup()} & Retrieves text of a (sub)match as a new string.\\
33 \ccode{esl\_regexp\_SubmatchCopy()} & Copies text of a (sub)match into a buffer.\\
34 \ccode{esl\_regexp\_SubmatchCoords()} & Retrieves start/end coord of a (sub)match.\\
35 \end{tabular}
36
37 \subsection{Examples of using the regexp API}
38
39 To use the \ccode{regexp} module, you first create a machine, which
40 you'll destroy when you're done. The same machine can be used for any
41 number of different patterns, so you would usually create just one
42 machine per function or code unit that needs regular expression
43 functionality.
44
45 An example of code that matches a \ccode{pattern} against a
46 \ccode{string} is:
47
48 \begin{cchunk}
49 #include <stdio.h> /* for printf() */
50 #include <easel/easel.h>
51 #include <easel/regexp.h>
52
53 int
54 main(int argc, char **argv)
55 {
56 ESL_REGEXP *m;
57 char *pattern;
58 char *string;
59 int status;
60 int i,j;
61
62 pattern = argv[1];
63 string = argv[2];
64
65 m = esl_regexp_Create();
66
67 status = esl_regexp_Match(m, pattern, string);
68
69 if (status == ESL_OK)
70 {
71 esl_regexp_SubmatchCoords(m, string, 0, &i, &j);
72 printf("Pattern matches string at positions %d..%d\n", i+1, j+1);
73 }
74 else if (status == ESL_EOD)
75 {
76 printf("Pattern does not match in string.\n");
77 }
78
79 esl_regexp_Destroy(m);
80 exit(0);
81 }
82 #endif /* ESL_REGEXP_EXAMPLE1*/
83 \end{cchunk}
84
85
86 The \ccode{esl\_regexp\_Match()} function does the parsing. It returns
87 \ccode{ESL\_OK} if a match is found, or \ccode{ESL\_EOD} if not.
88
89 If a match is found, information about where the match is located in
90 the string is kept in the machine. This information can be retrieved
91 by any of three functions: the start and end points of the match (or
92 any () token defining a submatch within the pattern) can be retrieved
93 by \ccode{esl\_regexp\_SubmatchCoords()}; a matching substring can be
94 retrieved as a new string by \ccode{esl\_regexp\_SubmatchDup()}, or
95 matching substring can be copied into an existing buffer by
96 \ccode{esl\_regexp\_SubmatchCopy()}. This information is volatile. It
97 will only be available for retrieval until the next time this machine
98 runs one of the two matching functions (\ccode{esl\_regexp\_Match()} or
99 \ccode{esl\_regexp\_MultipleMatches()}).
100
101 \ccode{esl\_regexp\_SubmatchCoords()} was called here with an argument
102 of \ccode{elem}$=$ 0, where 0 means the complete match, as opposed to
103 any tokens within the pattern. We'll see an example of retrieving
104 tokens in a bit.
105
106 The \ccode{i,j} start/end coordinates retrieved by the call to
107 \ccode{esl\_regexp\_SubmatchCoords()} are 0-offset relative to the
108 origin we provided, the \ccode{string} itself; so the first position
109 in \ccode{string} is $i=0$. We added $+1$ to \ccode{i,j} in the
110 example to print coords as $1..L$ in the string instead of $0..L-1$.
111
112 An example of running this code:
113
114 \begin{cchunk}
115 % ./example1 "ba(na)+" "grape banana apple"
116 Pattern matches string at positions 7..12
117 \end{cchunk}
118
119 Note that it matched ``banana'' from 7..12, not ``bana'' from
120 7..10. The Easel regexp machine is ``greedy''. It matches as much of
121 the string as the pattern allows. There isn't currently a way to
122 circumvent this to get minimal matching instead of maximal matching
123 (as, for instance, Perl regular expressions allow with an additional
124 '?' modifier on its greedy quantifiers.)
125
126 \subsubsection{Example of finding multiple matches in a string}
127
128 The example above only found one (the first) match in the target
129 string. What if you want to find every match in the string, analogous
130 to the Perl \ccode{m//g} operator? The combination of
131 \ccode{esl\_regexp\_Compile()} and
132 \ccode{esl\_regexp\_MultipleMatches()} provides a useful idiom for
133 this task, as seen in this example:
134
135 \begin{cchunk}
136 #include <stdio.h> /* for printf() */
137 #include <easel/easel.h>
138 #include <easel/regexp.h>
139
140 int
141 main(int argc, char **argv)
142 {
143 char *pattern;
144 char *string;
145 ESL_REGEXP *m;
146 int status;
147 int i,j;
148 char *s;
149 char buf[256];
150 int n = 0;
151
152 pattern = argv[1];
153 string = argv[2];
154
155 m = esl_regexp_Create();
156
157 esl_regexp_Compile(m, pattern);
158 s = string;
159 while ((status = esl_regexp_MultipleMatches(m, &s)) == ESL_OK)
160 {
161 n++;
162 esl_regexp_SubmatchCoords(m, string, 0, &i, &j);
163 esl_regexp_SubmatchCopy(m, 0, buf, 256);
164
165 printf("Match #%d: positions %d..%d sequence: %s\n", n, i+1, j+1, buf);
166 }
167
168 esl_regexp_Destroy(m);
169 exit(0);
170 }
171 \end{cchunk}
172
173 For example, something like this could parse a command line for one or
174 more arguments:
175
176 \begin{cchunk}
177 % ./example2 "-[^ ]+" "foo -a --arg -O myfile"
178 Match #1: positions 5..6 sequence: -a
179 Match #2: positions 8..12 sequence: --arg
180 Match #3: positions 14..15 sequence: -O
181 \end{cchunk}
182
183 Like \ccode{esl\_regexp\_Match()},
184 \ccode{esl\_regexp\_MultipleMatches()} finds the first match in a
185 string. Additionally, upon returning after finding a match,
186 \ccode{esl\_regexp\_MultipleMatches()} supplies a pointer to the next
187 position in the string following the match (through the \ccode{\&s}
188 argument). That facilitates writing an idiomatic \ccode{while ()} loop
189 that steps a temporary pointer \ccode{s} through the string until no
190 more matches are found, starting with \ccode{s = string}.
191
192 Using a regular expression pattern requires compiling it into machine
193 code (a non-deterministic finite automaton, NDFA). When you use
194 \ccode{esl\_regexp\_Match()}, your pattern is compiled, and the
195 resulting NDFA is run on your string to find a match. In the
196 multiple-matching case, it's a waste to recompile the pattern for
197 every match. Therefore, we use \ccode{esl\_regexp\_Compile()} to
198 compile the NDFA once and hold it in the machine, and
199 \ccode{esl\_regexp\_MultipleMatches()} takes a machine (containing a
200 precompiled NDFA) as an argument instead of a pattern.
201
202 Remember that the regexp machine is greedy, and that the pointer is set
203 to follow each match. Therefore, multiple matches are guaranteed to be
204 nonoverlapping, with each match matching as much of the string as it
205 can before a subsequent match occurs -- even if this is not what you
206 want.
207
208 Otherwise, \ccode{esl\_regexp\_MultipleMatches()} and
209 \ccode{esl\_regexp\_Match()} behave the same, in that they find the
210 first match in the string pointer they're provided, and in terms of
211 the information they leave in the machine for subsequent retrieval.
212
213 You can also see an example of \ccode{esl\_regexp\_SubmatchCopy()} in
214 action here, copying the complete match (``sub''match \#0), to a
215 provided fixed-length buffer.
216
217 \subsubsection{Example of parsing tokens out of a string}
218
219 Text parsing is laborious in C, a language which does not inherently
220 provide anywhere near the text-parsing power of Perl, for example.
221 Using a regular expression to match a line of text and extract one or
222 more tokens, demarcated by () in the expression, is a common operation
223 in Perl. The Easel regexp machine provides much of the same power. An
224 example of using token extraction:
225
226 \begin{cchunk}
227 #include <stdlib.h> /* for atoi() */
228 #include <stdio.h> /* for printf() */
229 #include <easel/easel.h>
230 #include <easel/regexp.h>
231
232 int
233 main(int argc, char **argv)
234 {
235 char *pattern;
236 char *string;
237 int ntok;
238 ESL_REGEXP *m;
239 int status;
240 int i,j;
241 char *token;
242 int n;
243
244 pattern = argv[1];
245 string = argv[2];
246 ntok = atoi(argv[3]);
247
248 m = esl_regexp_Create();
249
250 status = esl_regexp_Match(m, pattern, string);
251 if (status == ESL_OK)
252 {
253 for (n = 1; n <= ntok; n++)
254 {
255 esl_regexp_SubmatchCoords(m, string, n, &i, &j);
256 token = esl_regexp_SubmatchDup(m, n);
257 printf("token #%d: %d..%d, %s\n", n, i+1, j+1, token);
258 free(token);
259 }
260 }
261 esl_regexp_Destroy(m);
262 exit(0);
263 }
264 \end{cchunk}
265
266 In previous examples, we only retrieved information about ``submatch''
267 number 0, which always refers to the entire regular expression. The
268 machine also retains the same information about all the ()-demarcated
269 tokens in the expression, up to 15 of them.\footnote{The limit of one
270 complete expression plus 15 tokens is defined by a compile-time
271 constant \ccode{ESL\_REGEXP\_NSUB} in \ccode{regexp.h}, which is set to
272 16 by default.} Now, we tell the retrieval functions (here,
273 \ccode{esl\_regexp\_SubmatchCoords()} and
274 \ccode{esl\_regexp\_SubmatchDup()}) to retrieve info for token
275 \ccode{n} instead of 0.
276
277 For example, parsing a bibliographic reference like ``Gene
278 102:189-196(1991)'' might go something like:
279
280 \begin{cchunk}
281 % ./example3 "(\S+) (\d+):(\d+)-(\d+)\((\d+)\)" "Gene 102:189-196(1991)" 5
282 token #1: 1..4, Gene
283 token #2: 6..8, 102
284 token #3: 10..12, 189
285 token #4: 14..16, 196
286 token #5: 18..21, 1991
287 \end{cchunk}
288
289 The tokens are numbered in the order that their open-parenthesis
290 occurred in the expression, from left to right.
291
292 \subsection{Syntax of regular expressions}
293
294 Regular expression syntax is fairly universal and documented in many
295 places, but because different engines implement more or less rich sets
296 of regular expression operations, a specific description of Easel's
297 operators follows.
298
299 There are 11 metacharacters \verb'|?*+[().^$\' that encode regular
300 expression operations.
301
302 \ccode{.} is the ANY operator. It matches any single character.
303
304 \ccode{?}, \ccode{*}, and \ccode{+} are repetition operators that
305 follow some atom of the pattern. \ccode{?} means 0 or 1 occurrences of
306 the atom; \ccode{*} means 0 or more; \ccode{+} means 1 or more. For
307 example, \ccode{foo?} matches fo and foo; \ccode{foo*} matches fo,
308 foo, fooo, foooo and so on; \ccode{foo+} matches foo, fooo, foooo, and
309 so on.
310
311 \verb'^' is the beginning-of-string anchor, and \ccode{\$} is the
312 end-of-string anchor.
313
314 \ccode{|} is the concatenation operator, specifying alternative ways
315 to match. For example, \ccode{foo|bar|baz} matches baz, bar, or foo;
316 \ccode{(foo|bar|baz)+} matches barfoobaz, foofoofoo, etc.
317
318 \ccode{()} are for grouping and tokenizing. Anything inside \ccode{()}
319 is grouped and treated as a single atom for purposes of a subsequent
320 \ccode{?*+} operator, as in the \ccode{(foo|bar|baz)+} example above.
321 Anything inside \ccode{()} becomes a token, extractable by
322 \ccode{\_Submatch*} functions.
323
324 The backslash \verb+\+, when followed by any metacharacter (or in
325 fact, any non-alphanumeric character), specifies that that character
326 should be treated as an ordinary character. For example, the pattern
327 \verb+\\c:+ matches the string \verb+\c:+, since backslash is itself a
328 metacharacter.
329
330 A backslash followed by an alphanumeric character is either an
331 \emph{escape character} or a \emph{character set}. Four escape
332 characters are recognized: \verb+\f+ (form feed), \verb+\n+ (newline),
333 \verb+\r+ (carriage return), and \verb+\t+ (TAB). Six character set
334 codes are recognized, with the same meanings they have in Perl regular
335 expressions:
336
337 \begin{center}
338 \begin{tabular}{lll}
339 \textbf{code} & \textbf{meaning} & \textbf{equivalent to} \\
340 \verb+\d+ & digit & \verb+[0-9]+ \\
341 \verb+\D+ & not a digit & \verb+[^0-9]+ \\
342 \verb+\w+ & word character & \verb+[0-9a-z_a-Z]+ \\
343 \verb+\W+ & non-word character & \verb+[^0-9a-z_a-Z]+ \\
344 \verb+\s+ & whitespace & \verb+[ \t\n\r\f]+ \\
345 \verb+\S+ & non-whitespace & \verb+[^ \t\n\r\f]+ \\
346 \end{tabular}
347 \end{center}
348
349 A backslash that is followed by an alphanumeric character that is neither
350 an escape code or a character set code is an error.
351
352 \ccode{[} is the set (or range) operator. \footnote{An unmatched
353 \ccode{]} is not a metacharacter, but a \ccode{[} metacharacter always
354 implies a range and always must have a closing \ccode{]}.} The set of
355 characters inside brackets \ccode{[]} are read as a single ANYOF
356 atom. A set may be specified as a range of ASCII characters;
357 \ccode{[a-z]}, for example, means any lower-case character from a to
358 z, \ccode{[a-zA-Z]} means any alphabetic character, and \ccode{[0-9]}
359 means any digit. For example, \ccode{fo[ox]} matches foo or
360 fox. Additionally, \verb+[^+ implies the opposite, an ANYBUT atom: any
361 character \emph{except} the set of characters named is a match. For
362 example, \verb'foo[^ ]+' matches ``football'' in the string ``football
363 game''.
364
365 Metacharacters are handled differently inside the \verb+[]+ range
366 operator. The only special characters are \verb+]+, \verb+-+, and
367 \verb+\+. A \verb+]+ character indicates the end of the range operator
368 unless it immediately follows the \verb+[+, in which case it is
369 treated as a normal character (thus, weirdly, \verb+[][{}()]+ will
370 match any open/close brace/parenthesis character). The \verb+-+
371 character indicates the middle of a three-character \verb+x-y+ ASCII
372 range, unless it comes at the beginning or end of the range (thus
373 \verb+[]-]+ recognizes either \verb+]+ or \verb+-+ as literals). The
374 \verb+\+ character indicates an escaped character. Only five such
375 escape characters are recognized inside a range operator: \verb+\f+
376 (form feed), \verb+\n+ (newline), \verb+\r+ (carriage return),
377 \verb+\t+ (TAB), and \verb+\\+ (backslash itself). Character set codes
378 like \verb+\s+ are not allowed within range operators.
379
380
381
382
383
384
385
386