S390: Move utf8-utf32-z9.c to multiarch folder and use s390_libc_ifunc_expr macro.
[glibc.git] / manual / pattern.texi
blob30a76c8160353980c6d16cf77e3a01bd0f545ebb
1 @node Pattern Matching, I/O Overview, Searching and Sorting, Top
2 @c %MENU% Matching shell ``globs'' and regular expressions
3 @chapter Pattern Matching
5 @Theglibc{} provides pattern matching facilities for two kinds of
6 patterns: regular expressions and file-name wildcards.  The library also
7 provides a facility for expanding variable and command references and
8 parsing text into words in the way the shell does.
10 @menu
11 * Wildcard Matching::    Matching a wildcard pattern against a single string.
12 * Globbing::             Finding the files that match a wildcard pattern.
13 * Regular Expressions::  Matching regular expressions against strings.
14 * Word Expansion::       Expanding shell variables, nested commands,
15                             arithmetic, and wildcards.
16                             This is what the shell does with shell commands.
17 @end menu
19 @node Wildcard Matching
20 @section Wildcard Matching
22 @pindex fnmatch.h
23 This section describes how to match a wildcard pattern against a
24 particular string.  The result is a yes or no answer: does the
25 string fit the pattern or not.  The symbols described here are all
26 declared in @file{fnmatch.h}.
28 @comment fnmatch.h
29 @comment POSIX.2
30 @deftypefun int fnmatch (const char *@var{pattern}, const char *@var{string}, int @var{flags})
31 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
32 @c fnmatch @mtsenv @mtslocale @ascuheap @acsmem
33 @c  strnlen dup ok
34 @c  mbsrtowcs
35 @c  memset dup ok
36 @c  malloc dup @ascuheap @acsmem
37 @c  mbsinit dup ok
38 @c  free dup @ascuheap @acsmem
39 @c  FCT = internal_fnwmatch @mtsenv @mtslocale @ascuheap @acsmem
40 @c   FOLD @mtslocale
41 @c    towlower @mtslocale
42 @c   EXT @mtsenv @mtslocale @ascuheap @acsmem
43 @c    STRLEN = wcslen dup ok
44 @c    getenv @mtsenv
45 @c    malloc dup @ascuheap @acsmem
46 @c    MEMPCPY = wmempcpy dup ok
47 @c    FCT dup @mtsenv @mtslocale @ascuheap @acsmem
48 @c    STRCAT = wcscat dup ok
49 @c    free dup @ascuheap @acsmem
50 @c   END @mtsenv
51 @c    getenv @mtsenv
52 @c   MEMCHR = wmemchr dup ok
53 @c   getenv @mtsenv
54 @c   IS_CHAR_CLASS = is_char_class @mtslocale
55 @c    wctype @mtslocale
56 @c   BTOWC ok
57 @c   ISWCTYPE ok
58 @c   auto findidx dup ok
59 @c   elem_hash dup ok
60 @c   memcmp dup ok
61 @c   collseq_table_lookup dup ok
62 @c   NO_LEADING_PERIOD ok
63 This function tests whether the string @var{string} matches the pattern
64 @var{pattern}.  It returns @code{0} if they do match; otherwise, it
65 returns the nonzero value @code{FNM_NOMATCH}.  The arguments
66 @var{pattern} and @var{string} are both strings.
68 The argument @var{flags} is a combination of flag bits that alter the
69 details of matching.  See below for a list of the defined flags.
71 In @theglibc{}, @code{fnmatch} might sometimes report ``errors'' by
72 returning nonzero values that are not equal to @code{FNM_NOMATCH}.
73 @end deftypefun
75 These are the available flags for the @var{flags} argument:
77 @table @code
78 @comment fnmatch.h
79 @comment GNU
80 @item FNM_FILE_NAME
81 Treat the @samp{/} character specially, for matching file names.  If
82 this flag is set, wildcard constructs in @var{pattern} cannot match
83 @samp{/} in @var{string}.  Thus, the only way to match @samp{/} is with
84 an explicit @samp{/} in @var{pattern}.
86 @comment fnmatch.h
87 @comment POSIX.2
88 @item FNM_PATHNAME
89 This is an alias for @code{FNM_FILE_NAME}; it comes from POSIX.2.  We
90 don't recommend this name because we don't use the term ``pathname'' for
91 file names.
93 @comment fnmatch.h
94 @comment POSIX.2
95 @item FNM_PERIOD
96 Treat the @samp{.} character specially if it appears at the beginning of
97 @var{string}.  If this flag is set, wildcard constructs in @var{pattern}
98 cannot match @samp{.} as the first character of @var{string}.
100 If you set both @code{FNM_PERIOD} and @code{FNM_FILE_NAME}, then the
101 special treatment applies to @samp{.} following @samp{/} as well as to
102 @samp{.} at the beginning of @var{string}.  (The shell uses the
103 @code{FNM_PERIOD} and @code{FNM_FILE_NAME} flags together for matching
104 file names.)
106 @comment fnmatch.h
107 @comment POSIX.2
108 @item FNM_NOESCAPE
109 Don't treat the @samp{\} character specially in patterns.  Normally,
110 @samp{\} quotes the following character, turning off its special meaning
111 (if any) so that it matches only itself.  When quoting is enabled, the
112 pattern @samp{\?} matches only the string @samp{?}, because the question
113 mark in the pattern acts like an ordinary character.
115 If you use @code{FNM_NOESCAPE}, then @samp{\} is an ordinary character.
117 @comment fnmatch.h
118 @comment GNU
119 @item FNM_LEADING_DIR
120 Ignore a trailing sequence of characters starting with a @samp{/} in
121 @var{string}; that is to say, test whether @var{string} starts with a
122 directory name that @var{pattern} matches.
124 If this flag is set, either @samp{foo*} or @samp{foobar} as a pattern
125 would match the string @samp{foobar/frobozz}.
127 @comment fnmatch.h
128 @comment GNU
129 @item FNM_CASEFOLD
130 Ignore case in comparing @var{string} to @var{pattern}.
132 @comment fnmatch.h
133 @comment GNU
134 @item FNM_EXTMATCH
135 @cindex Korn Shell
136 @pindex ksh
137 Besides the normal patterns, also recognize the extended patterns
138 introduced in @file{ksh}.  The patterns are written in the form
139 explained in the following table where @var{pattern-list} is a @code{|}
140 separated list of patterns.
142 @table @code
143 @item ?(@var{pattern-list})
144 The pattern matches if zero or one occurrences of any of the patterns
145 in the @var{pattern-list} allow matching the input string.
147 @item *(@var{pattern-list})
148 The pattern matches if zero or more occurrences of any of the patterns
149 in the @var{pattern-list} allow matching the input string.
151 @item +(@var{pattern-list})
152 The pattern matches if one or more occurrences of any of the patterns
153 in the @var{pattern-list} allow matching the input string.
155 @item @@(@var{pattern-list})
156 The pattern matches if exactly one occurrence of any of the patterns in
157 the @var{pattern-list} allows matching the input string.
159 @item !(@var{pattern-list})
160 The pattern matches if the input string cannot be matched with any of
161 the patterns in the @var{pattern-list}.
162 @end table
163 @end table
165 @node Globbing
166 @section Globbing
168 @cindex globbing
169 The archetypal use of wildcards is for matching against the files in a
170 directory, and making a list of all the matches.  This is called
171 @dfn{globbing}.
173 You could do this using @code{fnmatch}, by reading the directory entries
174 one by one and testing each one with @code{fnmatch}.  But that would be
175 slow (and complex, since you would have to handle subdirectories by
176 hand).
178 The library provides a function @code{glob} to make this particular use
179 of wildcards convenient.  @code{glob} and the other symbols in this
180 section are declared in @file{glob.h}.
182 @menu
183 * Calling Glob::             Basic use of @code{glob}.
184 * Flags for Globbing::       Flags that enable various options in @code{glob}.
185 * More Flags for Globbing::  GNU specific extensions to @code{glob}.
186 @end menu
188 @node Calling Glob
189 @subsection Calling @code{glob}
191 The result of globbing is a vector of file names (strings).  To return
192 this vector, @code{glob} uses a special data type, @code{glob_t}, which
193 is a structure.  You pass @code{glob} the address of the structure, and
194 it fills in the structure's fields to tell you about the results.
196 @comment glob.h
197 @comment POSIX.2
198 @deftp {Data Type} glob_t
199 This data type holds a pointer to a word vector.  More precisely, it
200 records both the address of the word vector and its size.  The GNU
201 implementation contains some more fields which are non-standard
202 extensions.
204 @table @code
205 @item gl_pathc
206 The number of elements in the vector, excluding the initial null entries
207 if the GLOB_DOOFFS flag is used (see gl_offs below).
209 @item gl_pathv
210 The address of the vector.  This field has type @w{@code{char **}}.
212 @item gl_offs
213 The offset of the first real element of the vector, from its nominal
214 address in the @code{gl_pathv} field.  Unlike the other fields, this
215 is always an input to @code{glob}, rather than an output from it.
217 If you use a nonzero offset, then that many elements at the beginning of
218 the vector are left empty.  (The @code{glob} function fills them with
219 null pointers.)
221 The @code{gl_offs} field is meaningful only if you use the
222 @code{GLOB_DOOFFS} flag.  Otherwise, the offset is always zero
223 regardless of what is in this field, and the first real element comes at
224 the beginning of the vector.
226 @item gl_closedir
227 The address of an alternative implementation of the @code{closedir}
228 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
229 the flag parameter.  The type of this field is
230 @w{@code{void (*) (void *)}}.
232 This is a GNU extension.
234 @item gl_readdir
235 The address of an alternative implementation of the @code{readdir}
236 function used to read the contents of a directory.  It is used if the
237 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
238 this field is @w{@code{struct dirent *(*) (void *)}}.
240 An implementation of @code{gl_readdir} needs to initialize the following
241 members of the @code{struct dirent} object:
243 @table @code
244 @item d_type
245 This member should be set to the file type of the entry if it is known.
246 Otherwise, the value @code{DT_UNKNOWN} can be used.  The @code{glob}
247 function may use the specified file type to avoid callbacks in cases
248 where the file type indicates that the data is not required.
250 @item d_ino
251 This member needs to be non-zero, otherwise @code{glob} may skip the
252 current entry and call the @code{gl_readdir} callback function again to
253 retrieve another entry.
255 @item d_name
256 This member must be set to the name of the entry.  It must be
257 null-terminated.
258 @end table
260 The example below shows how to allocate a @code{struct dirent} object
261 containing a given name.
263 @smallexample
264 @include mkdirent.c.texi
265 @end smallexample
267 The @code{glob} function reads the @code{struct dirent} members listed
268 above and makes a copy of the file name in the @code{d_name} member
269 immediately after the @code{gl_readdir} callback function returns.
270 Future invocations of any of the callback functions may dealloacte or
271 reuse the buffer.  It is the responsibility of the caller of the
272 @code{glob} function to allocate and deallocate the buffer, around the
273 call to @code{glob} or using the callback functions.  For example, an
274 application could allocate the buffer in the @code{gl_readdir} callback
275 function, and deallocate it in the @code{gl_closedir} callback function.
277 The @code{gl_readdir} member is a GNU extension.
279 @item gl_opendir
280 The address of an alternative implementation of the @code{opendir}
281 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
282 the flag parameter.  The type of this field is
283 @w{@code{void *(*) (const char *)}}.
285 This is a GNU extension.
287 @item gl_stat
288 The address of an alternative implementation of the @code{stat} function
289 to get information about an object in the filesystem.  It is used if the
290 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
291 this field is @w{@code{int (*) (const char *, struct stat *)}}.
293 This is a GNU extension.
295 @item gl_lstat
296 The address of an alternative implementation of the @code{lstat}
297 function to get information about an object in the filesystems, not
298 following symbolic links.  It is used if the @code{GLOB_ALTDIRFUNC} bit
299 is set in the flag parameter.  The type of this field is @code{@w{int
300 (*) (const char *,} @w{struct stat *)}}.
302 This is a GNU extension.
304 @item gl_flags
305 The flags used when @code{glob} was called.  In addition, @code{GLOB_MAGCHAR}
306 might be set.  See @ref{Flags for Globbing} for more details.
308 This is a GNU extension.
309 @end table
310 @end deftp
312 For use in the @code{glob64} function @file{glob.h} contains another
313 definition for a very similar type.  @code{glob64_t} differs from
314 @code{glob_t} only in the types of the members @code{gl_readdir},
315 @code{gl_stat}, and @code{gl_lstat}.
317 @comment glob.h
318 @comment GNU
319 @deftp {Data Type} glob64_t
320 This data type holds a pointer to a word vector.  More precisely, it
321 records both the address of the word vector and its size.  The GNU
322 implementation contains some more fields which are non-standard
323 extensions.
325 @table @code
326 @item gl_pathc
327 The number of elements in the vector, excluding the initial null entries
328 if the GLOB_DOOFFS flag is used (see gl_offs below).
330 @item gl_pathv
331 The address of the vector.  This field has type @w{@code{char **}}.
333 @item gl_offs
334 The offset of the first real element of the vector, from its nominal
335 address in the @code{gl_pathv} field.  Unlike the other fields, this
336 is always an input to @code{glob}, rather than an output from it.
338 If you use a nonzero offset, then that many elements at the beginning of
339 the vector are left empty.  (The @code{glob} function fills them with
340 null pointers.)
342 The @code{gl_offs} field is meaningful only if you use the
343 @code{GLOB_DOOFFS} flag.  Otherwise, the offset is always zero
344 regardless of what is in this field, and the first real element comes at
345 the beginning of the vector.
347 @item gl_closedir
348 The address of an alternative implementation of the @code{closedir}
349 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
350 the flag parameter.  The type of this field is
351 @w{@code{void (*) (void *)}}.
353 This is a GNU extension.
355 @item gl_readdir
356 The address of an alternative implementation of the @code{readdir64}
357 function used to read the contents of a directory.  It is used if the
358 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
359 this field is @w{@code{struct dirent64 *(*) (void *)}}.
361 This is a GNU extension.
363 @item gl_opendir
364 The address of an alternative implementation of the @code{opendir}
365 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
366 the flag parameter.  The type of this field is
367 @w{@code{void *(*) (const char *)}}.
369 This is a GNU extension.
371 @item gl_stat
372 The address of an alternative implementation of the @code{stat64} function
373 to get information about an object in the filesystem.  It is used if the
374 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
375 this field is @w{@code{int (*) (const char *, struct stat64 *)}}.
377 This is a GNU extension.
379 @item gl_lstat
380 The address of an alternative implementation of the @code{lstat64}
381 function to get information about an object in the filesystems, not
382 following symbolic links.  It is used if the @code{GLOB_ALTDIRFUNC} bit
383 is set in the flag parameter.  The type of this field is @code{@w{int
384 (*) (const char *,} @w{struct stat64 *)}}.
386 This is a GNU extension.
388 @item gl_flags
389 The flags used when @code{glob} was called.  In addition, @code{GLOB_MAGCHAR}
390 might be set.  See @ref{Flags for Globbing} for more details.
392 This is a GNU extension.
393 @end table
394 @end deftp
396 @comment glob.h
397 @comment POSIX.2
398 @deftypefun int glob (const char *@var{pattern}, int @var{flags}, int (*@var{errfunc}) (const char *@var{filename}, int @var{error-code}), glob_t *@var{vector-ptr})
399 @safety{@prelim{}@mtunsafe{@mtasurace{:utent} @mtsenv{} @mtascusig{:ALRM} @mtascutimer{} @mtslocale{}}@asunsafe{@ascudlopen{} @ascuplugin{} @asucorrupt{} @ascuheap{} @asulock{}}@acunsafe{@acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
400 @c glob @mtasurace:utent @mtsenv @mtascusig:ALRM @mtascutimer @mtslocale @ascudlopen @ascuplugin @asucorrupt @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
401 @c  strlen dup ok
402 @c  strchr dup ok
403 @c  malloc dup @ascuheap @acsmem
404 @c  mempcpy dup ok
405 @c  next_brace_sub ok
406 @c  free dup @ascuheap @acsmem
407 @c  globfree dup @asucorrupt @ascuheap @acucorrupt @acsmem
408 @c  glob_pattern_p ok
409 @c   glob_pattern_type dup ok
410 @c  getenv dup @mtsenv
411 @c  GET_LOGIN_NAME_MAX ok
412 @c  getlogin_r dup @mtasurace:utent @mtascusig:ALRM @mtascutimer @mtslocale @ascudlopen @ascuplugin @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
413 @c  GETPW_R_SIZE_MAX ok
414 @c  getpwnam_r dup @mtslocale @ascudlopen @ascuplugin @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
415 @c  realloc dup @ascuheap @acsmem
416 @c  memcpy dup ok
417 @c  memchr dup ok
418 @c  *pglob->gl_stat user-supplied
419 @c  stat64 dup ok
420 @c  S_ISDIR dup ok
421 @c  strdup dup @ascuheap @acsmem
422 @c  glob_pattern_type ok
423 @c  glob_in_dir @mtsenv @mtslocale @asucorrupt @ascuheap @acucorrupt @acsfd @acsmem
424 @c   strlen dup ok
425 @c   glob_pattern_type dup ok
426 @c   malloc dup @ascuheap @acsmem
427 @c   mempcpy dup ok
428 @c   *pglob->gl_stat user-supplied
429 @c   stat64 dup ok
430 @c   free dup @ascuheap @acsmem
431 @c   *pglob->gl_opendir user-supplied
432 @c   opendir dup @ascuheap @acsmem @acsfd
433 @c   dirfd dup ok
434 @c   *pglob->gl_readdir user-supplied
435 @c   CONVERT_DIRENT_DIRENT64 ok
436 @c   readdir64 ok [protected by exclusive use of the stream]
437 @c   REAL_DIR_ENTRY ok
438 @c   DIRENT_MIGHT_BE_DIR ok
439 @c   fnmatch dup @mtsenv @mtslocale @ascuheap @acsmem
440 @c   DIRENT_MIGHT_BE_SYMLINK ok
441 @c   link_exists_p ok
442 @c    link_exists2_p ok
443 @c     strlen dup ok
444 @c     mempcpy dup ok
445 @c     *pglob->gl_stat user-supplied
446 @c    fxstatat64 dup ok
447 @c   realloc dup @ascuheap @acsmem
448 @c   pglob->gl_closedir user-supplied
449 @c   closedir @ascuheap @acsmem @acsfd
450 @c  prefix_array dup @asucorrupt @ascuheap @acucorrupt @acsmem
451 @c   strlen dup ok
452 @c   malloc dup @ascuheap @acsmem
453 @c   free dup @ascuheap @acsmem
454 @c   mempcpy dup ok
455 @c  strcpy dup ok
456 The function @code{glob} does globbing using the pattern @var{pattern}
457 in the current directory.  It puts the result in a newly allocated
458 vector, and stores the size and address of this vector into
459 @code{*@var{vector-ptr}}.  The argument @var{flags} is a combination of
460 bit flags; see @ref{Flags for Globbing}, for details of the flags.
462 The result of globbing is a sequence of file names.  The function
463 @code{glob} allocates a string for each resulting word, then
464 allocates a vector of type @code{char **} to store the addresses of
465 these strings.  The last element of the vector is a null pointer.
466 This vector is called the @dfn{word vector}.
468 To return this vector, @code{glob} stores both its address and its
469 length (number of elements, not counting the terminating null pointer)
470 into @code{*@var{vector-ptr}}.
472 Normally, @code{glob} sorts the file names alphabetically before
473 returning them.  You can turn this off with the flag @code{GLOB_NOSORT}
474 if you want to get the information as fast as possible.  Usually it's
475 a good idea to let @code{glob} sort them---if you process the files in
476 alphabetical order, the users will have a feel for the rate of progress
477 that your application is making.
479 If @code{glob} succeeds, it returns 0.  Otherwise, it returns one
480 of these error codes:
482 @vtable @code
483 @comment glob.h
484 @comment POSIX.2
485 @item GLOB_ABORTED
486 There was an error opening a directory, and you used the flag
487 @code{GLOB_ERR} or your specified @var{errfunc} returned a nonzero
488 value.
489 @iftex
490 See below
491 @end iftex
492 @ifinfo
493 @xref{Flags for Globbing},
494 @end ifinfo
495 for an explanation of the @code{GLOB_ERR} flag and @var{errfunc}.
497 @comment glob.h
498 @comment POSIX.2
499 @item GLOB_NOMATCH
500 The pattern didn't match any existing files.  If you use the
501 @code{GLOB_NOCHECK} flag, then you never get this error code, because
502 that flag tells @code{glob} to @emph{pretend} that the pattern matched
503 at least one file.
505 @comment glob.h
506 @comment POSIX.2
507 @item GLOB_NOSPACE
508 It was impossible to allocate memory to hold the result.
509 @end vtable
511 In the event of an error, @code{glob} stores information in
512 @code{*@var{vector-ptr}} about all the matches it has found so far.
514 It is important to notice that the @code{glob} function will not fail if
515 it encounters directories or files which cannot be handled without the
516 LFS interfaces.  The implementation of @code{glob} is supposed to use
517 these functions internally.  This at least is the assumption made by
518 the Unix standard.  The GNU extension of allowing the user to provide their
519 own directory handling and @code{stat} functions complicates things a
520 bit.  If these callback functions are used and a large file or directory
521 is encountered @code{glob} @emph{can} fail.
522 @end deftypefun
524 @comment glob.h
525 @comment GNU
526 @deftypefun int glob64 (const char *@var{pattern}, int @var{flags}, int (*@var{errfunc}) (const char *@var{filename}, int @var{error-code}), glob64_t *@var{vector-ptr})
527 @safety{@prelim{}@mtunsafe{@mtasurace{:utent} @mtsenv{} @mtascusig{:ALRM} @mtascutimer{} @mtslocale{}}@asunsafe{@ascudlopen{} @asucorrupt{} @ascuheap{} @asulock{}}@acunsafe{@acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
528 @c Same code as glob, but with glob64_t #defined as glob_t.
529 The @code{glob64} function was added as part of the Large File Summit
530 extensions but is not part of the original LFS proposal.  The reason for
531 this is simple: it is not necessary.  The necessity for a @code{glob64}
532 function is added by the extensions of the GNU @code{glob}
533 implementation which allows the user to provide their own directory handling
534 and @code{stat} functions.  The @code{readdir} and @code{stat} functions
535 do depend on the choice of @code{_FILE_OFFSET_BITS} since the definition
536 of the types @code{struct dirent} and @code{struct stat} will change
537 depending on the choice.
539 Besides this difference, @code{glob64} works just like @code{glob} in
540 all aspects.
542 This function is a GNU extension.
543 @end deftypefun
545 @node Flags for Globbing
546 @subsection Flags for Globbing
548 This section describes the standard flags that you can specify in the
549 @var{flags} argument to @code{glob}.  Choose the flags you want,
550 and combine them with the C bitwise OR operator @code{|}.
552 Note that there are @ref{More Flags for Globbing} available as GNU extensions.
554 @vtable @code
555 @comment glob.h
556 @comment POSIX.2
557 @item GLOB_APPEND
558 Append the words from this expansion to the vector of words produced by
559 previous calls to @code{glob}.  This way you can effectively expand
560 several words as if they were concatenated with spaces between them.
562 In order for appending to work, you must not modify the contents of the
563 word vector structure between calls to @code{glob}.  And, if you set
564 @code{GLOB_DOOFFS} in the first call to @code{glob}, you must also
565 set it when you append to the results.
567 Note that the pointer stored in @code{gl_pathv} may no longer be valid
568 after you call @code{glob} the second time, because @code{glob} might
569 have relocated the vector.  So always fetch @code{gl_pathv} from the
570 @code{glob_t} structure after each @code{glob} call; @strong{never} save
571 the pointer across calls.
573 @comment glob.h
574 @comment POSIX.2
575 @item GLOB_DOOFFS
576 Leave blank slots at the beginning of the vector of words.
577 The @code{gl_offs} field says how many slots to leave.
578 The blank slots contain null pointers.
580 @comment glob.h
581 @comment POSIX.2
582 @item GLOB_ERR
583 Give up right away and report an error if there is any difficulty
584 reading the directories that must be read in order to expand @var{pattern}
585 fully.  Such difficulties might include a directory in which you don't
586 have the requisite access.  Normally, @code{glob} tries its best to keep
587 on going despite any errors, reading whatever directories it can.
589 You can exercise even more control than this by specifying an
590 error-handler function @var{errfunc} when you call @code{glob}.  If
591 @var{errfunc} is not a null pointer, then @code{glob} doesn't give up
592 right away when it can't read a directory; instead, it calls
593 @var{errfunc} with two arguments, like this:
595 @smallexample
596 (*@var{errfunc}) (@var{filename}, @var{error-code})
597 @end smallexample
599 @noindent
600 The argument @var{filename} is the name of the directory that
601 @code{glob} couldn't open or couldn't read, and @var{error-code} is the
602 @code{errno} value that was reported to @code{glob}.
604 If the error handler function returns nonzero, then @code{glob} gives up
605 right away.  Otherwise, it continues.
607 @comment glob.h
608 @comment POSIX.2
609 @item GLOB_MARK
610 If the pattern matches the name of a directory, append @samp{/} to the
611 directory's name when returning it.
613 @comment glob.h
614 @comment POSIX.2
615 @item GLOB_NOCHECK
616 If the pattern doesn't match any file names, return the pattern itself
617 as if it were a file name that had been matched.  (Normally, when the
618 pattern doesn't match anything, @code{glob} returns that there were no
619 matches.)
621 @comment glob.h
622 @comment POSIX.2
623 @item GLOB_NOESCAPE
624 Don't treat the @samp{\} character specially in patterns.  Normally,
625 @samp{\} quotes the following character, turning off its special meaning
626 (if any) so that it matches only itself.  When quoting is enabled, the
627 pattern @samp{\?} matches only the string @samp{?}, because the question
628 mark in the pattern acts like an ordinary character.
630 If you use @code{GLOB_NOESCAPE}, then @samp{\} is an ordinary character.
632 @code{glob} does its work by calling the function @code{fnmatch}
633 repeatedly.  It handles the flag @code{GLOB_NOESCAPE} by turning on the
634 @code{FNM_NOESCAPE} flag in calls to @code{fnmatch}.
636 @comment glob.h
637 @comment POSIX.2
638 @item GLOB_NOSORT
639 Don't sort the file names; return them in no particular order.
640 (In practice, the order will depend on the order of the entries in
641 the directory.)  The only reason @emph{not} to sort is to save time.
642 @end vtable
644 @node More Flags for Globbing
645 @subsection More Flags for Globbing
647 Beside the flags described in the last section, the GNU implementation of
648 @code{glob} allows a few more flags which are also defined in the
649 @file{glob.h} file.  Some of the extensions implement functionality
650 which is available in modern shell implementations.
652 @vtable @code
653 @comment glob.h
654 @comment GNU
655 @item GLOB_PERIOD
656 The @code{.} character (period) is treated special.  It cannot be
657 matched by wildcards.  @xref{Wildcard Matching}, @code{FNM_PERIOD}.
659 @comment glob.h
660 @comment GNU
661 @item GLOB_MAGCHAR
662 The @code{GLOB_MAGCHAR} value is not to be given to @code{glob} in the
663 @var{flags} parameter.  Instead, @code{glob} sets this bit in the
664 @var{gl_flags} element of the @var{glob_t} structure provided as the
665 result if the pattern used for matching contains any wildcard character.
667 @comment glob.h
668 @comment GNU
669 @item GLOB_ALTDIRFUNC
670 Instead of using the normal functions for accessing the
671 filesystem the @code{glob} implementation uses the user-supplied
672 functions specified in the structure pointed to by @var{pglob}
673 parameter.  For more information about the functions refer to the
674 sections about directory handling see @ref{Accessing Directories}, and
675 @ref{Reading Attributes}.
677 @comment glob.h
678 @comment GNU
679 @item GLOB_BRACE
680 If this flag is given, the handling of braces in the pattern is changed.
681 It is now required that braces appear correctly grouped.  I.e., for each
682 opening brace there must be a closing one.  Braces can be used
683 recursively.  So it is possible to define one brace expression in
684 another one.  It is important to note that the range of each brace
685 expression is completely contained in the outer brace expression (if
686 there is one).
688 The string between the matching braces is separated into single
689 expressions by splitting at @code{,} (comma) characters.  The commas
690 themselves are discarded.  Please note what we said above about recursive
691 brace expressions.  The commas used to separate the subexpressions must
692 be at the same level.  Commas in brace subexpressions are not matched.
693 They are used during expansion of the brace expression of the deeper
694 level.  The example below shows this
696 @smallexample
697 glob ("@{foo/@{,bar,biz@},baz@}", GLOB_BRACE, NULL, &result)
698 @end smallexample
700 @noindent
701 is equivalent to the sequence
703 @smallexample
704 glob ("foo/", GLOB_BRACE, NULL, &result)
705 glob ("foo/bar", GLOB_BRACE|GLOB_APPEND, NULL, &result)
706 glob ("foo/biz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
707 glob ("baz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
708 @end smallexample
710 @noindent
711 if we leave aside error handling.
713 @comment glob.h
714 @comment GNU
715 @item GLOB_NOMAGIC
716 If the pattern contains no wildcard constructs (it is a literal file name),
717 return it as the sole ``matching'' word, even if no file exists by that name.
719 @comment glob.h
720 @comment GNU
721 @item GLOB_TILDE
722 If this flag is used the character @code{~} (tilde) is handled specially
723 if it appears at the beginning of the pattern.  Instead of being taken
724 verbatim it is used to represent the home directory of a known user.
726 If @code{~} is the only character in pattern or it is followed by a
727 @code{/} (slash), the home directory of the process owner is
728 substituted.  Using @code{getlogin} and @code{getpwnam} the information
729 is read from the system databases.  As an example take user @code{bart}
730 with his home directory at @file{/home/bart}.  For him a call like
732 @smallexample
733 glob ("~/bin/*", GLOB_TILDE, NULL, &result)
734 @end smallexample
736 @noindent
737 would return the contents of the directory @file{/home/bart/bin}.
738 Instead of referring to the own home directory it is also possible to
739 name the home directory of other users.  To do so one has to append the
740 user name after the tilde character.  So the contents of user
741 @code{homer}'s @file{bin} directory can be retrieved by
743 @smallexample
744 glob ("~homer/bin/*", GLOB_TILDE, NULL, &result)
745 @end smallexample
747 If the user name is not valid or the home directory cannot be determined
748 for some reason the pattern is left untouched and itself used as the
749 result.  I.e., if in the last example @code{home} is not available the
750 tilde expansion yields to @code{"~homer/bin/*"} and @code{glob} is not
751 looking for a directory named @code{~homer}.
753 This functionality is equivalent to what is available in C-shells if the
754 @code{nonomatch} flag is set.
756 @comment glob.h
757 @comment GNU
758 @item GLOB_TILDE_CHECK
759 If this flag is used @code{glob} behaves as if @code{GLOB_TILDE} is
760 given.  The only difference is that if the user name is not available or
761 the home directory cannot be determined for other reasons this leads to
762 an error.  @code{glob} will return @code{GLOB_NOMATCH} instead of using
763 the pattern itself as the name.
765 This functionality is equivalent to what is available in C-shells if
766 the @code{nonomatch} flag is not set.
768 @comment glob.h
769 @comment GNU
770 @item GLOB_ONLYDIR
771 If this flag is used the globbing function takes this as a
772 @strong{hint} that the caller is only interested in directories
773 matching the pattern.  If the information about the type of the file
774 is easily available non-directories will be rejected but no extra
775 work will be done to determine the information for each file.  I.e.,
776 the caller must still be able to filter directories out.
778 This functionality is only available with the GNU @code{glob}
779 implementation.  It is mainly used internally to increase the
780 performance but might be useful for a user as well and therefore is
781 documented here.
782 @end vtable
784 Calling @code{glob} will in most cases allocate resources which are used
785 to represent the result of the function call.  If the same object of
786 type @code{glob_t} is used in multiple call to @code{glob} the resources
787 are freed or reused so that no leaks appear.  But this does not include
788 the time when all @code{glob} calls are done.
790 @comment glob.h
791 @comment POSIX.2
792 @deftypefun void globfree (glob_t *@var{pglob})
793 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
794 @c globfree dup @asucorrupt @ascuheap @acucorrupt @acsmem
795 @c  free dup @ascuheap @acsmem
796 The @code{globfree} function frees all resources allocated by previous
797 calls to @code{glob} associated with the object pointed to by
798 @var{pglob}.  This function should be called whenever the currently used
799 @code{glob_t} typed object isn't used anymore.
800 @end deftypefun
802 @comment glob.h
803 @comment GNU
804 @deftypefun void globfree64 (glob64_t *@var{pglob})
805 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @asulock{}}@acunsafe{@acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
806 This function is equivalent to @code{globfree} but it frees records of
807 type @code{glob64_t} which were allocated by @code{glob64}.
808 @end deftypefun
811 @node Regular Expressions
812 @section Regular Expression Matching
814 @Theglibc{} supports two interfaces for matching regular
815 expressions.  One is the standard POSIX.2 interface, and the other is
816 what @theglibc{} has had for many years.
818 Both interfaces are declared in the header file @file{regex.h}.
819 If you define @w{@code{_POSIX_C_SOURCE}}, then only the POSIX.2
820 functions, structures, and constants are declared.
821 @c !!! we only document the POSIX.2 interface here!!
823 @menu
824 * POSIX Regexp Compilation::    Using @code{regcomp} to prepare to match.
825 * Flags for POSIX Regexps::     Syntax variations for @code{regcomp}.
826 * Matching POSIX Regexps::      Using @code{regexec} to match the compiled
827                                    pattern that you get from @code{regcomp}.
828 * Regexp Subexpressions::       Finding which parts of the string were matched.
829 * Subexpression Complications:: Find points of which parts were matched.
830 * Regexp Cleanup::              Freeing storage; reporting errors.
831 @end menu
833 @node POSIX Regexp Compilation
834 @subsection POSIX Regular Expression Compilation
836 Before you can actually match a regular expression, you must
837 @dfn{compile} it.  This is not true compilation---it produces a special
838 data structure, not machine instructions.  But it is like ordinary
839 compilation in that its purpose is to enable you to ``execute'' the
840 pattern fast.  (@xref{Matching POSIX Regexps}, for how to use the
841 compiled regular expression for matching.)
843 There is a special data type for compiled regular expressions:
845 @comment regex.h
846 @comment POSIX.2
847 @deftp {Data Type} regex_t
848 This type of object holds a compiled regular expression.
849 It is actually a structure.  It has just one field that your programs
850 should look at:
852 @table @code
853 @item re_nsub
854 This field holds the number of parenthetical subexpressions in the
855 regular expression that was compiled.
856 @end table
858 There are several other fields, but we don't describe them here, because
859 only the functions in the library should use them.
860 @end deftp
862 After you create a @code{regex_t} object, you can compile a regular
863 expression into it by calling @code{regcomp}.
865 @comment regex.h
866 @comment POSIX.2
867 @deftypefun int regcomp (regex_t *restrict @var{compiled}, const char *restrict @var{pattern}, int @var{cflags})
868 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
869 @c All of the issues have to do with memory allocation and multi-byte
870 @c character handling present in the input string, or implied by ranges
871 @c or inverted character classes.
872 @c (re_)malloc @ascuheap @acsmem
873 @c re_compile_internal @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
874 @c  (re_)realloc @ascuheap @acsmem [no @asucorrupt @acucorrupt for we zero the buffer]
875 @c  init_dfa @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
876 @c   (re_)malloc @ascuheap @acsmem
877 @c   calloc @ascuheap @acsmem
878 @c   _NL_CURRENT ok
879 @c   _NL_CURRENT_WORD ok
880 @c   btowc @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
881 @c  libc_lock_init ok
882 @c  re_string_construct @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
883 @c   re_string_construct_common ok
884 @c   re_string_realloc_buffers @ascuheap @acsmem
885 @c    (re_)realloc dup @ascuheap @acsmem
886 @c   build_wcs_upper_buffer @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
887 @c    isascii ok
888 @c    mbsinit ok
889 @c    toupper ok
890 @c    mbrtowc dup @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
891 @c    iswlower @mtslocale
892 @c    towupper @mtslocale
893 @c    wcrtomb dup @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
894 @c    (re_)malloc dup @ascuheap @acsmem
895 @c   build_upper_buffer ok (@mtslocale but optimized)
896 @c    islower ok
897 @c    toupper ok
898 @c   build_wcs_buffer @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
899 @c    mbrtowc dup @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
900 @c   re_string_translate_buffer ok
901 @c  parse @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
902 @c   fetch_token @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
903 @c    peek_token @mtslocale
904 @c     re_string_eoi ok
905 @c     re_string_peek_byte ok
906 @c     re_string_cur_idx ok
907 @c     re_string_length ok
908 @c     re_string_peek_byte_case @mtslocale
909 @c      re_string_peek_byte dup ok
910 @c      re_string_is_single_byte_char ok
911 @c      isascii ok
912 @c      re_string_peek_byte dup ok
913 @c     re_string_wchar_at ok
914 @c     re_string_skip_bytes ok
915 @c    re_string_skip_bytes dup ok
916 @c   parse_reg_exp @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
917 @c    parse_branch @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
918 @c     parse_expression @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
919 @c      create_token_tree dup @ascuheap @acsmem
920 @c      re_string_eoi dup ok
921 @c      re_string_first_byte ok
922 @c      fetch_token dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
923 @c      create_tree dup @ascuheap @acsmem
924 @c      parse_sub_exp @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
925 @c       fetch_token dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
926 @c       parse_reg_exp dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
927 @c       postorder() @ascuheap @acsmem
928 @c        free_tree @ascuheap @acsmem
929 @c         free_token dup @ascuheap @acsmem
930 @c       create_tree dup @ascuheap @acsmem
931 @c      parse_bracket_exp @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
932 @c       _NL_CURRENT dup ok
933 @c       _NL_CURRENT_WORD dup ok
934 @c       calloc dup @ascuheap @acsmem
935 @c       (re_)free dup @ascuheap @acsmem
936 @c       peek_token_bracket ok
937 @c        re_string_eoi dup ok
938 @c        re_string_peek_byte dup ok
939 @c        re_string_first_byte dup ok
940 @c        re_string_cur_idx dup ok
941 @c        re_string_length dup ok
942 @c        re_string_skip_bytes dup ok
943 @c       bitset_set ok
944 @c       re_string_skip_bytes ok
945 @c       parse_bracket_element @mtslocale
946 @c        re_string_char_size_at ok
947 @c        re_string_wchar_at dup ok
948 @c        re_string_skip_bytes dup ok
949 @c        parse_bracket_symbol @mtslocale
950 @c         re_string_eoi dup ok
951 @c         re_string_fetch_byte_case @mtslocale
952 @c          re_string_fetch_byte ok
953 @c          re_string_first_byte dup ok
954 @c          isascii ok
955 @c          re_string_char_size_at dup ok
956 @c          re_string_skip_bytes dup ok
957 @c         re_string_fetch_byte dup ok
958 @c         re_string_peek_byte dup ok
959 @c         re_string_skip_bytes dup ok
960 @c        peek_token_bracket dup ok
961 @c       auto build_range_exp @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
962 @c        auto lookup_collation_sequence_value @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
963 @c         btowc dup @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
964 @c         collseq_table_lookup ok
965 @c         auto seek_collating_symbol_entry dup ok
966 @c        (re_)realloc dup @ascuheap @acsmem
967 @c        collseq_table_lookup dup ok
968 @c       bitset_set dup ok
969 @c       (re_)realloc dup @ascuheap @acsmem
970 @c       build_equiv_class @mtslocale @ascuheap @acsmem
971 @c        _NL_CURRENT ok
972 @c        auto findidx ok
973 @c        bitset_set dup ok
974 @c        (re_)realloc dup @ascuheap @acsmem
975 @c       auto build_collating_symbol @ascuheap @acsmem
976 @c        auto seek_collating_symbol_entry ok
977 @c        bitset_set dup ok
978 @c        (re_)realloc dup @ascuheap @acsmem
979 @c       build_charclass @mtslocale @ascuheap @acsmem
980 @c        (re_)realloc dup @ascuheap @acsmem
981 @c        bitset_set dup ok
982 @c        isalnum ok
983 @c        iscntrl ok
984 @c        isspace ok
985 @c        isalpha ok
986 @c        isdigit ok
987 @c        isprint ok
988 @c        isupper ok
989 @c        isblank ok
990 @c        isgraph ok
991 @c        ispunct ok
992 @c        isxdigit ok
993 @c       bitset_not ok
994 @c       bitset_mask ok
995 @c       create_token_tree dup @ascuheap @acsmem
996 @c       create_tree dup @ascuheap @acsmem
997 @c       free_charset dup @ascuheap @acsmem
998 @c      init_word_char @mtslocale
999 @c       isalnum ok
1000 @c      build_charclass_op @mtslocale @ascuheap @acsmem
1001 @c       calloc dup @ascuheap @acsmem
1002 @c       build_charclass dup @mtslocale @ascuheap @acsmem
1003 @c       (re_)free dup @ascuheap @acsmem
1004 @c       free_charset dup @ascuheap @acsmem
1005 @c       bitset_set dup ok
1006 @c       bitset_not dup ok
1007 @c       bitset_mask dup ok
1008 @c       create_token_tree dup @ascuheap @acsmem
1009 @c       create_tree dup @ascuheap @acsmem
1010 @c      parse_dup_op @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1011 @c       re_string_cur_idx dup ok
1012 @c       fetch_number @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1013 @c        fetch_token dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1014 @c       re_string_set_index ok
1015 @c       postorder() @ascuheap @acsmem
1016 @c        free_tree dup @ascuheap @acsmem
1017 @c        mark_opt_subexp ok
1018 @c       duplicate_tree @ascuheap @acsmem
1019 @c        create_token_tree dup @ascuheap @acsmem
1020 @c       create_tree dup @ascuheap @acsmem
1021 @c     postorder() @ascuheap @acsmem
1022 @c      free_tree dup @ascuheap @acsmem
1023 @c    fetch_token dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1024 @c    parse_branch dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1025 @c    create_tree dup @ascuheap @acsmem
1026 @c   create_tree @ascuheap @acsmem
1027 @c    create_token_tree @ascuheap @acsmem
1028 @c     (re_)malloc dup @ascuheap @acsmem
1029 @c  analyze @ascuheap @acsmem
1030 @c   (re_)malloc dup @ascuheap @acsmem
1031 @c   preorder() @ascuheap @acsmem
1032 @c    optimize_subexps ok
1033 @c    calc_next ok
1034 @c    link_nfa_nodes @ascuheap @acsmem
1035 @c     re_node_set_init_1 @ascuheap @acsmem
1036 @c      (re_)malloc dup @ascuheap @acsmem
1037 @c     re_node_set_init_2 @ascuheap @acsmem
1038 @c      (re_)malloc dup @ascuheap @acsmem
1039 @c   postorder() @ascuheap @acsmem
1040 @c    lower_subexps @ascuheap @acsmem
1041 @c     lower_subexp @ascuheap @acsmem
1042 @c      create_tree dup @ascuheap @acsmem
1043 @c    calc_first @ascuheap @acsmem
1044 @c     re_dfa_add_node @ascuheap @acsmem
1045 @c      (re_)realloc dup @ascuheap @acsmem
1046 @c      re_node_set_init_empty ok
1047 @c   calc_eclosure @ascuheap @acsmem
1048 @c    calc_eclosure_iter @ascuheap @acsmem
1049 @c     re_node_set_alloc @ascuheap @acsmem
1050 @c      (re_)malloc dup @ascuheap @acsmem
1051 @c     duplicate_node_closure @ascuheap @acsmem
1052 @c      re_node_set_empty ok
1053 @c      duplicate_node @ascuheap @acsmem
1054 @c       re_dfa_add_node dup @ascuheap @acsmem
1055 @c      re_node_set_insert @ascuheap @acsmem
1056 @c       (re_)realloc dup @ascuheap @acsmem
1057 @c      search_duplicated_node ok
1058 @c     re_node_set_merge @ascuheap @acsmem
1059 @c      (re_)realloc dup @ascuheap @acsmem
1060 @c     re_node_set_free @ascuheap @acsmem
1061 @c      (re_)free dup @ascuheap @acsmem
1062 @c     re_node_set_insert dup @ascuheap @acsmem
1063 @c    re_node_set_free dup @ascuheap @acsmem
1064 @c   calc_inveclosure @ascuheap @acsmem
1065 @c    re_node_set_init_empty dup ok
1066 @c    re_node_set_insert_last @ascuheap @acsmem
1067 @c     (re_)realloc dup @ascuheap @acsmem
1068 @c  optimize_utf8 ok
1069 @c  create_initial_state @ascuheap @acsmem
1070 @c   re_node_set_init_copy @ascuheap @acsmem
1071 @c    (re_)malloc dup @ascuheap @acsmem
1072 @c    re_node_set_init_empty dup ok
1073 @c   re_node_set_contains ok
1074 @c   re_node_set_merge dup @ascuheap @acsmem
1075 @c   re_acquire_state_context @ascuheap @acsmem
1076 @c    calc_state_hash ok
1077 @c    re_node_set_compare ok
1078 @c    create_cd_newstate @ascuheap @acsmem
1079 @c     calloc dup @ascuheap @acsmem
1080 @c     re_node_set_init_copy dup @ascuheap @acsmem
1081 @c     (re_)free dup @ascuheap @acsmem
1082 @c     free_state @ascuheap @acsmem
1083 @c      re_node_set_free dup @ascuheap @acsmem
1084 @c      (re_)free dup @ascuheap @acsmem
1085 @c     NOT_SATISFY_PREV_CONSTRAINT ok
1086 @c     re_node_set_remove_at ok
1087 @c     register_state @ascuheap @acsmem
1088 @c      re_node_set_alloc dup @ascuheap @acsmem
1089 @c      re_node_set_insert_last dup @ascuheap @acsmem
1090 @c      (re_)realloc dup @ascuheap @acsmem
1091 @c   re_node_set_free dup @ascuheap @acsmem
1092 @c  free_workarea_compile @ascuheap @acsmem
1093 @c   (re_)free dup @ascuheap @acsmem
1094 @c  re_string_destruct @ascuheap @acsmem
1095 @c   (re_)free dup @ascuheap @acsmem
1096 @c  free_dfa_content @ascuheap @acsmem
1097 @c   free_token @ascuheap @acsmem
1098 @c    free_charset @ascuheap @acsmem
1099 @c     (re_)free dup @ascuheap @acsmem
1100 @c    (re_)free dup @ascuheap @acsmem
1101 @c   (re_)free dup @ascuheap @acsmem
1102 @c   re_node_set_free dup @ascuheap @acsmem
1103 @c re_compile_fastmap @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1104 @c  re_compile_fastmap_iter @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1105 @c   re_set_fastmap ok
1106 @c    tolower ok
1107 @c   mbrtowc dup @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1108 @c   wcrtomb dup @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1109 @c   towlower @mtslocale
1110 @c   _NL_CURRENT ok
1111 @c (re_)free @ascuheap @acsmem
1112 The function @code{regcomp} ``compiles'' a regular expression into a
1113 data structure that you can use with @code{regexec} to match against a
1114 string.  The compiled regular expression format is designed for
1115 efficient matching.  @code{regcomp} stores it into @code{*@var{compiled}}.
1117 It's up to you to allocate an object of type @code{regex_t} and pass its
1118 address to @code{regcomp}.
1120 The argument @var{cflags} lets you specify various options that control
1121 the syntax and semantics of regular expressions.  @xref{Flags for POSIX
1122 Regexps}.
1124 If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from
1125 the compiled regular expression the information necessary to record
1126 how subexpressions actually match.  In this case, you might as well
1127 pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when
1128 you call @code{regexec}.
1130 If you don't use @code{REG_NOSUB}, then the compiled regular expression
1131 does have the capacity to record how subexpressions match.  Also,
1132 @code{regcomp} tells you how many subexpressions @var{pattern} has, by
1133 storing the number in @code{@var{compiled}->re_nsub}.  You can use that
1134 value to decide how long an array to allocate to hold information about
1135 subexpression matches.
1137 @code{regcomp} returns @code{0} if it succeeds in compiling the regular
1138 expression; otherwise, it returns a nonzero error code (see the table
1139 below).  You can use @code{regerror} to produce an error message string
1140 describing the reason for a nonzero value; see @ref{Regexp Cleanup}.
1142 @end deftypefun
1144 Here are the possible nonzero values that @code{regcomp} can return:
1146 @table @code
1147 @comment regex.h
1148 @comment POSIX.2
1149 @item REG_BADBR
1150 There was an invalid @samp{\@{@dots{}\@}} construct in the regular
1151 expression.  A valid @samp{\@{@dots{}\@}} construct must contain either
1152 a single number, or two numbers in increasing order separated by a
1153 comma.
1155 @comment regex.h
1156 @comment POSIX.2
1157 @item REG_BADPAT
1158 There was a syntax error in the regular expression.
1160 @comment regex.h
1161 @comment POSIX.2
1162 @item REG_BADRPT
1163 A repetition operator such as @samp{?} or @samp{*} appeared in a bad
1164 position (with no preceding subexpression to act on).
1166 @comment regex.h
1167 @comment POSIX.2
1168 @item REG_ECOLLATE
1169 The regular expression referred to an invalid collating element (one not
1170 defined in the current locale for string collation).  @xref{Locale
1171 Categories}.
1173 @comment regex.h
1174 @comment POSIX.2
1175 @item REG_ECTYPE
1176 The regular expression referred to an invalid character class name.
1178 @comment regex.h
1179 @comment POSIX.2
1180 @item REG_EESCAPE
1181 The regular expression ended with @samp{\}.
1183 @comment regex.h
1184 @comment POSIX.2
1185 @item REG_ESUBREG
1186 There was an invalid number in the @samp{\@var{digit}} construct.
1188 @comment regex.h
1189 @comment POSIX.2
1190 @item REG_EBRACK
1191 There were unbalanced square brackets in the regular expression.
1193 @comment regex.h
1194 @comment POSIX.2
1195 @item REG_EPAREN
1196 An extended regular expression had unbalanced parentheses,
1197 or a basic regular expression had unbalanced @samp{\(} and @samp{\)}.
1199 @comment regex.h
1200 @comment POSIX.2
1201 @item REG_EBRACE
1202 The regular expression had unbalanced @samp{\@{} and @samp{\@}}.
1204 @comment regex.h
1205 @comment POSIX.2
1206 @item REG_ERANGE
1207 One of the endpoints in a range expression was invalid.
1209 @comment regex.h
1210 @comment POSIX.2
1211 @item REG_ESPACE
1212 @code{regcomp} ran out of memory.
1213 @end table
1215 @node Flags for POSIX Regexps
1216 @subsection Flags for POSIX Regular Expressions
1218 These are the bit flags that you can use in the @var{cflags} operand when
1219 compiling a regular expression with @code{regcomp}.
1221 @table @code
1222 @comment regex.h
1223 @comment POSIX.2
1224 @item REG_EXTENDED
1225 Treat the pattern as an extended regular expression, rather than as a
1226 basic regular expression.
1228 @comment regex.h
1229 @comment POSIX.2
1230 @item REG_ICASE
1231 Ignore case when matching letters.
1233 @comment regex.h
1234 @comment POSIX.2
1235 @item REG_NOSUB
1236 Don't bother storing the contents of the @var{matchptr} array.
1238 @comment regex.h
1239 @comment POSIX.2
1240 @item REG_NEWLINE
1241 Treat a newline in @var{string} as dividing @var{string} into multiple
1242 lines, so that @samp{$} can match before the newline and @samp{^} can
1243 match after.  Also, don't permit @samp{.} to match a newline, and don't
1244 permit @samp{[^@dots{}]} to match a newline.
1246 Otherwise, newline acts like any other ordinary character.
1247 @end table
1249 @node Matching POSIX Regexps
1250 @subsection Matching a Compiled POSIX Regular Expression
1252 Once you have compiled a regular expression, as described in @ref{POSIX
1253 Regexp Compilation}, you can match it against strings using
1254 @code{regexec}.  A match anywhere inside the string counts as success,
1255 unless the regular expression contains anchor characters (@samp{^} or
1256 @samp{$}).
1258 @comment regex.h
1259 @comment POSIX.2
1260 @deftypefun int regexec (const regex_t *restrict @var{compiled}, const char *restrict @var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr}[restrict], int @var{eflags})
1261 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1262 @c libc_lock_lock @asulock @aculock
1263 @c re_search_internal @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1264 @c  re_string_allocate @ascuheap @acsmem
1265 @c   re_string_construct_common dup ok
1266 @c   re_string_realloc_buffers dup @ascuheap @acsmem
1267 @c  match_ctx_init @ascuheap @acsmem
1268 @c   (re_)malloc dup @ascuheap @acsmem
1269 @c  re_string_byte_at ok
1270 @c  re_string_first_byte dup ok
1271 @c  check_matching @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1272 @c   re_string_cur_idx dup ok
1273 @c   acquire_init_state_context dup @ascuheap @acsmem
1274 @c    re_string_context_at ok
1275 @c     re_string_byte_at dup ok
1276 @c     bitset_contain ok
1277 @c    re_acquire_state_context dup @ascuheap @acsmem
1278 @c   check_subexp_matching_top @ascuheap @acsmem
1279 @c    match_ctx_add_subtop @ascuheap @acsmem
1280 @c     (re_)realloc dup @ascuheap @acsmem
1281 @c     calloc dup @ascuheap @acsmem
1282 @c   transit_state_bkref @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1283 @c    re_string_cur_idx dup ok
1284 @c    re_string_context_at dup ok
1285 @c    NOT_SATISFY_NEXT_CONSTRAINT ok
1286 @c    get_subexp @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1287 @c     re_string_get_buffer ok
1288 @c     search_cur_bkref_entry ok
1289 @c     clean_state_log_if_needed @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1290 @c      extend_buffers @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1291 @c       re_string_realloc_buffers dup @ascuheap @acsmem
1292 @c       (re_)realloc dup @ascuheap @acsmem
1293 @c       build_wcs_upper_buffer dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1294 @c       build_upper_buffer dup ok (@mtslocale but optimized)
1295 @c       build_wcs_buffer dup @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1296 @c       re_string_translate_buffer dup ok
1297 @c     get_subexp_sub @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1298 @c      check_arrival @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1299 @c       (re_)realloc dup @ascuheap @acsmem
1300 @c       re_string_context_at dup ok
1301 @c       re_node_set_init_1 dup @ascuheap @acsmem
1302 @c       check_arrival_expand_ecl @ascuheap @acsmem
1303 @c        re_node_set_alloc dup @ascuheap @acsmem
1304 @c        find_subexp_node ok
1305 @c        re_node_set_merge dup @ascuheap @acsmem
1306 @c        re_node_set_free dup @ascuheap @acsmem
1307 @c        check_arrival_expand_ecl_sub @ascuheap @acsmem
1308 @c         re_node_set_contains dup ok
1309 @c         re_node_set_insert dup @ascuheap @acsmem
1310 @c       re_node_set_free dup @ascuheap @acsmem
1311 @c       re_node_set_init_copy dup @ascuheap @acsmem
1312 @c       re_node_set_init_empty dup ok
1313 @c       expand_bkref_cache @ascuheap @acsmem
1314 @c        search_cur_bkref_entry dup ok
1315 @c        re_node_set_contains dup ok
1316 @c        re_node_set_init_1 dup @ascuheap @acsmem
1317 @c        check_arrival_expand_ecl dup @ascuheap @acsmem
1318 @c        re_node_set_merge dup @ascuheap @acsmem
1319 @c        re_node_set_init_copy dup @ascuheap @acsmem
1320 @c        re_node_set_insert dup @ascuheap @acsmem
1321 @c        re_node_set_free dup @ascuheap @acsmem
1322 @c        re_acquire_state @ascuheap @acsmem
1323 @c         calc_state_hash dup ok
1324 @c         re_node_set_compare dup ok
1325 @c         create_ci_newstate @ascuheap @acsmem
1326 @c          calloc dup @ascuheap @acsmem
1327 @c          re_node_set_init_copy dup @ascuheap @acsmem
1328 @c          (re_)free dup @ascuheap @acsmem
1329 @c          register_state dup @ascuheap @acsmem
1330 @c          free_state dup @ascuheap @acsmem
1331 @c       re_acquire_state_context dup @ascuheap @acsmem
1332 @c       re_node_set_merge dup @ascuheap @acsmem
1333 @c       check_arrival_add_next_nodes @mtslocale @ascuheap @acsmem
1334 @c        re_node_set_init_empty dup ok
1335 @c        check_node_accept_bytes @mtslocale @ascuheap @acsmem
1336 @c         re_string_byte_at dup ok
1337 @c         re_string_char_size_at dup ok
1338 @c         re_string_elem_size_at @mtslocale
1339 @c          _NL_CURRENT_WORD dup ok
1340 @c          _NL_CURRENT dup ok
1341 @c          auto findidx dup ok
1342 @c         _NL_CURRENT_WORD dup ok
1343 @c         _NL_CURRENT dup ok
1344 @c         collseq_table_lookup dup ok
1345 @c         find_collation_sequence_value @mtslocale
1346 @c          _NL_CURRENT_WORD dup ok
1347 @c          _NL_CURRENT dup ok
1348 @c         auto findidx dup ok
1349 @c         wcscoll @mtslocale @ascuheap @acsmem
1350 @c        re_node_set_empty dup ok
1351 @c        re_node_set_merge dup @ascuheap @acsmem
1352 @c        re_node_set_free dup @ascuheap @acsmem
1353 @c        re_node_set_insert dup @ascuheap @acsmem
1354 @c        re_acquire_state dup @ascuheap @acsmem
1355 @c        check_node_accept ok
1356 @c         re_string_byte_at dup ok
1357 @c         bitset_contain dup ok
1358 @c         re_string_context_at dup ok
1359 @c         NOT_SATISFY_NEXT_CONSTRAINT dup ok
1360 @c      match_ctx_add_entry @ascuheap @acsmem
1361 @c       (re_)realloc dup @ascuheap @acsmem
1362 @c       (re_)free dup @ascuheap @acsmem
1363 @c      clean_state_log_if_needed dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1364 @c     extend_buffers dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1365 @c     find_subexp_node dup ok
1366 @c     calloc dup @ascuheap @acsmem
1367 @c     check_arrival dup ***
1368 @c     match_ctx_add_sublast @ascuheap @acsmem
1369 @c      (re_)realloc dup @ascuheap @acsmem
1370 @c    re_acquire_state_context dup @ascuheap @acsmem
1371 @c    re_node_set_init_union @ascuheap @acsmem
1372 @c     (re_)malloc dup @ascuheap @acsmem
1373 @c     re_node_set_init_copy dup @ascuheap @acsmem
1374 @c     re_node_set_init_empty dup ok
1375 @c    re_node_set_free dup @ascuheap @acsmem
1376 @c    check_subexp_matching_top dup @ascuheap @acsmem
1377 @c   check_halt_state_context ok
1378 @c    re_string_context_at dup ok
1379 @c    check_halt_node_context ok
1380 @c     NOT_SATISFY_NEXT_CONSTRAINT dup ok
1381 @c   re_string_eoi dup ok
1382 @c   extend_buffers dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1383 @c   transit_state @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1384 @c    transit_state_mb @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1385 @c     re_string_context_at dup ok
1386 @c     NOT_SATISFY_NEXT_CONSTRAINT dup ok
1387 @c     check_node_accept_bytes dup @mtslocale @ascuheap @acsmem
1388 @c     re_string_cur_idx dup ok
1389 @c     clean_state_log_if_needed @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1390 @c     re_node_set_init_union dup @ascuheap @acsmem
1391 @c     re_acquire_state_context dup @ascuheap @acsmem
1392 @c    re_string_fetch_byte dup ok
1393 @c    re_string_context_at dup ok
1394 @c    build_trtable @ascuheap @acsmem
1395 @c     (re_)malloc dup @ascuheap @acsmem
1396 @c     group_nodes_into_DFAstates @ascuheap @acsmem
1397 @c      bitset_empty dup ok
1398 @c      bitset_set dup ok
1399 @c      bitset_merge dup ok
1400 @c      bitset_set_all ok
1401 @c      bitset_clear ok
1402 @c      bitset_contain dup ok
1403 @c      bitset_copy ok
1404 @c      re_node_set_init_copy dup @ascuheap @acsmem
1405 @c      re_node_set_insert dup @ascuheap @acsmem
1406 @c      re_node_set_init_1 dup @ascuheap @acsmem
1407 @c      re_node_set_free dup @ascuheap @acsmem
1408 @c     re_node_set_alloc dup @ascuheap @acsmem
1409 @c     malloc dup @ascuheap @acsmem
1410 @c     free dup @ascuheap @acsmem
1411 @c     re_node_set_free dup @ascuheap @acsmem
1412 @c     bitset_empty ok
1413 @c     re_node_set_empty dup ok
1414 @c     re_node_set_merge dup @ascuheap @acsmem
1415 @c     re_acquire_state_context dup @ascuheap @acsmem
1416 @c     bitset_merge ok
1417 @c     calloc dup @ascuheap @acsmem
1418 @c     bitset_contain dup ok
1419 @c   merge_state_with_log @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1420 @c    re_string_cur_idx dup ok
1421 @c    re_node_set_init_union dup @ascuheap @acsmem
1422 @c    re_string_context_at dup ok
1423 @c    re_node_set_free dup @ascuheap @acsmem
1424 @c    check_subexp_matching_top @ascuheap @acsmem
1425 @c     match_ctx_add_subtop dup @ascuheap @acsmem
1426 @c    transit_state_bkref dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1427 @c   find_recover_state
1428 @c    re_string_cur_idx dup ok
1429 @c    re_string_skip_bytes dup ok
1430 @c    merge_state_with_log dup @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1431 @c  check_halt_state_context dup ok
1432 @c  prune_impossible_nodes @mtslocale @ascuheap @acsmem
1433 @c   (re_)malloc dup @ascuheap @acsmem
1434 @c   sift_ctx_init ok
1435 @c    re_node_set_init_empty dup ok
1436 @c   sift_states_backward @mtslocale @ascuheap @acsmem
1437 @c    re_node_set_init_1 dup @ascuheap @acsmem
1438 @c    update_cur_sifted_state @mtslocale @ascuheap @acsmem
1439 @c     add_epsilon_src_nodes @ascuheap @acsmem
1440 @c      re_acquire_state dup @ascuheap @acsmem
1441 @c      re_node_set_alloc dup @ascuheap @acsmem
1442 @c      re_node_set_merge dup @ascuheap @acsmem
1443 @c      re_node_set_add_intersect @ascuheap @acsmem
1444 @c       (re_)realloc dup @ascuheap @acsmem
1445 @c     check_subexp_limits @ascuheap @acsmem
1446 @c      sub_epsilon_src_nodes @ascuheap @acsmem
1447 @c       re_node_set_init_empty dup ok
1448 @c       re_node_set_contains dup ok
1449 @c       re_node_set_add_intersect dup @ascuheap @acsmem
1450 @c       re_node_set_free dup @ascuheap @acsmem
1451 @c       re_node_set_remove_at dup ok
1452 @c      re_node_set_contains dup ok
1453 @c     re_acquire_state dup @ascuheap @acsmem
1454 @c     sift_states_bkref @mtslocale @ascuheap @acsmem
1455 @c      search_cur_bkref_entry dup ok
1456 @c      check_dst_limits ok
1457 @c       search_cur_bkref_entry dup ok
1458 @c       check_dst_limits_calc_pos ok
1459 @c        check_dst_limits_calc_pos_1 ok
1460 @c      re_node_set_init_copy dup @ascuheap @acsmem
1461 @c      re_node_set_insert dup @ascuheap @acsmem
1462 @c      sift_states_backward dup @mtslocale @ascuheap @acsmem
1463 @c      merge_state_array dup @ascuheap @acsmem
1464 @c      re_node_set_remove ok
1465 @c       re_node_set_contains dup ok
1466 @c       re_node_set_remove_at dup ok
1467 @c      re_node_set_free dup @ascuheap @acsmem
1468 @c    re_node_set_free dup @ascuheap @acsmem
1469 @c    re_node_set_empty dup ok
1470 @c    build_sifted_states @mtslocale @ascuheap @acsmem
1471 @c     sift_states_iter_mb @mtslocale @ascuheap @acsmem
1472 @c      check_node_accept_bytes dup @mtslocale @ascuheap @acsmem
1473 @c     check_node_accept dup ok
1474 @c     check_dst_limits dup ok
1475 @c     re_node_set_insert dup @ascuheap @acsmem
1476 @c   re_node_set_free dup @ascuheap @acsmem
1477 @c   check_halt_state_context dup ok
1478 @c   merge_state_array @ascuheap @acsmem
1479 @c    re_node_set_init_union dup @ascuheap @acsmem
1480 @c    re_acquire_state dup @ascuheap @acsmem
1481 @c    re_node_set_free dup @ascuheap @acsmem
1482 @c   (re_)free dup @ascuheap @acsmem
1483 @c  set_regs @ascuheap @acsmem
1484 @c   (re_)malloc dup @ascuheap @acsmem
1485 @c   re_node_set_init_empty dup ok
1486 @c   free_fail_stack_return @ascuheap @acsmem
1487 @c    re_node_set_free dup @ascuheap @acsmem
1488 @c    (re_)free dup @ascuheap @acsmem
1489 @c   update_regs ok
1490 @c   re_node_set_free dup @ascuheap @acsmem
1491 @c   pop_fail_stack @ascuheap @acsmem
1492 @c    re_node_set_free dup @ascuheap @acsmem
1493 @c    (re_)free dup @ascuheap @acsmem
1494 @c   (re_)free dup @ascuheap @acsmem
1495 @c  (re_)free dup @ascuheap @acsmem
1496 @c  match_ctx_free @ascuheap @acsmem
1497 @c   match_ctx_clean @ascuheap @acsmem
1498 @c    (re_)free dup @ascuheap @acsmem
1499 @c   (re_)free dup @ascuheap @acsmem
1500 @c  re_string_destruct dup @ascuheap @acsmem
1501 @c libc_lock_unlock @aculock
1502 This function tries to match the compiled regular expression
1503 @code{*@var{compiled}} against @var{string}.
1505 @code{regexec} returns @code{0} if the regular expression matches;
1506 otherwise, it returns a nonzero value.  See the table below for
1507 what nonzero values mean.  You can use @code{regerror} to produce an
1508 error message string describing the reason for a nonzero value;
1509 see @ref{Regexp Cleanup}.
1511 The argument @var{eflags} is a word of bit flags that enable various
1512 options.
1514 If you want to get information about what part of @var{string} actually
1515 matched the regular expression or its subexpressions, use the arguments
1516 @var{matchptr} and @var{nmatch}.  Otherwise, pass @code{0} for
1517 @var{nmatch}, and @code{NULL} for @var{matchptr}.  @xref{Regexp
1518 Subexpressions}.
1519 @end deftypefun
1521 You must match the regular expression with the same set of current
1522 locales that were in effect when you compiled the regular expression.
1524 The function @code{regexec} accepts the following flags in the
1525 @var{eflags} argument:
1527 @table @code
1528 @comment regex.h
1529 @comment POSIX.2
1530 @item REG_NOTBOL
1531 Do not regard the beginning of the specified string as the beginning of
1532 a line; more generally, don't make any assumptions about what text might
1533 precede it.
1535 @comment regex.h
1536 @comment POSIX.2
1537 @item REG_NOTEOL
1538 Do not regard the end of the specified string as the end of a line; more
1539 generally, don't make any assumptions about what text might follow it.
1540 @end table
1542 Here are the possible nonzero values that @code{regexec} can return:
1544 @table @code
1545 @comment regex.h
1546 @comment POSIX.2
1547 @item REG_NOMATCH
1548 The pattern didn't match the string.  This isn't really an error.
1550 @comment regex.h
1551 @comment POSIX.2
1552 @item REG_ESPACE
1553 @code{regexec} ran out of memory.
1554 @end table
1556 @node Regexp Subexpressions
1557 @subsection Match Results with Subexpressions
1559 When @code{regexec} matches parenthetical subexpressions of
1560 @var{pattern}, it records which parts of @var{string} they match.  It
1561 returns that information by storing the offsets into an array whose
1562 elements are structures of type @code{regmatch_t}.  The first element of
1563 the array (index @code{0}) records the part of the string that matched
1564 the entire regular expression.  Each other element of the array records
1565 the beginning and end of the part that matched a single parenthetical
1566 subexpression.
1568 @comment regex.h
1569 @comment POSIX.2
1570 @deftp {Data Type} regmatch_t
1571 This is the data type of the @var{matchptr} array that you pass to
1572 @code{regexec}.  It contains two structure fields, as follows:
1574 @table @code
1575 @item rm_so
1576 The offset in @var{string} of the beginning of a substring.  Add this
1577 value to @var{string} to get the address of that part.
1579 @item rm_eo
1580 The offset in @var{string} of the end of the substring.
1581 @end table
1582 @end deftp
1584 @comment regex.h
1585 @comment POSIX.2
1586 @deftp {Data Type} regoff_t
1587 @code{regoff_t} is an alias for another signed integer type.
1588 The fields of @code{regmatch_t} have type @code{regoff_t}.
1589 @end deftp
1591 The @code{regmatch_t} elements correspond to subexpressions
1592 positionally; the first element (index @code{1}) records where the first
1593 subexpression matched, the second element records the second
1594 subexpression, and so on.  The order of the subexpressions is the order
1595 in which they begin.
1597 When you call @code{regexec}, you specify how long the @var{matchptr}
1598 array is, with the @var{nmatch} argument.  This tells @code{regexec} how
1599 many elements to store.  If the actual regular expression has more than
1600 @var{nmatch} subexpressions, then you won't get offset information about
1601 the rest of them.  But this doesn't alter whether the pattern matches a
1602 particular string or not.
1604 If you don't want @code{regexec} to return any information about where
1605 the subexpressions matched, you can either supply @code{0} for
1606 @var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the
1607 pattern with @code{regcomp}.
1609 @node Subexpression Complications
1610 @subsection Complications in Subexpression Matching
1612 Sometimes a subexpression matches a substring of no characters.  This
1613 happens when @samp{f\(o*\)} matches the string @samp{fum}.  (It really
1614 matches just the @samp{f}.)  In this case, both of the offsets identify
1615 the point in the string where the null substring was found.  In this
1616 example, the offsets are both @code{1}.
1618 Sometimes the entire regular expression can match without using some of
1619 its subexpressions at all---for example, when @samp{ba\(na\)*} matches the
1620 string @samp{ba}, the parenthetical subexpression is not used.  When
1621 this happens, @code{regexec} stores @code{-1} in both fields of the
1622 element for that subexpression.
1624 Sometimes matching the entire regular expression can match a particular
1625 subexpression more than once---for example, when @samp{ba\(na\)*}
1626 matches the string @samp{bananana}, the parenthetical subexpression
1627 matches three times.  When this happens, @code{regexec} usually stores
1628 the offsets of the last part of the string that matched the
1629 subexpression.  In the case of @samp{bananana}, these offsets are
1630 @code{6} and @code{8}.
1632 But the last match is not always the one that is chosen.  It's more
1633 accurate to say that the last @emph{opportunity} to match is the one
1634 that takes precedence.  What this means is that when one subexpression
1635 appears within another, then the results reported for the inner
1636 subexpression reflect whatever happened on the last match of the outer
1637 subexpression.  For an example, consider @samp{\(ba\(na\)*s \)*} matching
1638 the string @samp{bananas bas }.  The last time the inner expression
1639 actually matches is near the end of the first word.  But it is
1640 @emph{considered} again in the second word, and fails to match there.
1641 @code{regexec} reports nonuse of the ``na'' subexpression.
1643 Another place where this rule applies is when the regular expression
1644 @smallexample
1645 \(ba\(na\)*s \|nefer\(ti\)* \)*
1646 @end smallexample
1647 @noindent
1648 matches @samp{bananas nefertiti}.  The ``na'' subexpression does match
1649 in the first word, but it doesn't match in the second word because the
1650 other alternative is used there.  Once again, the second repetition of
1651 the outer subexpression overrides the first, and within that second
1652 repetition, the ``na'' subexpression is not used.  So @code{regexec}
1653 reports nonuse of the ``na'' subexpression.
1655 @node Regexp Cleanup
1656 @subsection POSIX Regexp Matching Cleanup
1658 When you are finished using a compiled regular expression, you can
1659 free the storage it uses by calling @code{regfree}.
1661 @comment regex.h
1662 @comment POSIX.2
1663 @deftypefun void regfree (regex_t *@var{compiled})
1664 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1665 @c (re_)free dup @ascuheap @acsmem
1666 @c free_dfa_content dup @ascuheap @acsmem
1667 Calling @code{regfree} frees all the storage that @code{*@var{compiled}}
1668 points to.  This includes various internal fields of the @code{regex_t}
1669 structure that aren't documented in this manual.
1671 @code{regfree} does not free the object @code{*@var{compiled}} itself.
1672 @end deftypefun
1674 You should always free the space in a @code{regex_t} structure with
1675 @code{regfree} before using the structure to compile another regular
1676 expression.
1678 When @code{regcomp} or @code{regexec} reports an error, you can use
1679 the function @code{regerror} to turn it into an error message string.
1681 @comment regex.h
1682 @comment POSIX.2
1683 @deftypefun size_t regerror (int @var{errcode}, const regex_t *restrict @var{compiled}, char *restrict @var{buffer}, size_t @var{length})
1684 @safety{@prelim{}@mtsafe{@mtsenv{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
1685 @c regerror calls gettext, strcmp and mempcpy or memcpy.
1686 This function produces an error message string for the error code
1687 @var{errcode}, and stores the string in @var{length} bytes of memory
1688 starting at @var{buffer}.  For the @var{compiled} argument, supply the
1689 same compiled regular expression structure that @code{regcomp} or
1690 @code{regexec} was working with when it got the error.  Alternatively,
1691 you can supply @code{NULL} for @var{compiled}; you will still get a
1692 meaningful error message, but it might not be as detailed.
1694 If the error message can't fit in @var{length} bytes (including a
1695 terminating null character), then @code{regerror} truncates it.
1696 The string that @code{regerror} stores is always null-terminated
1697 even if it has been truncated.
1699 The return value of @code{regerror} is the minimum length needed to
1700 store the entire error message.  If this is less than @var{length}, then
1701 the error message was not truncated, and you can use it.  Otherwise, you
1702 should call @code{regerror} again with a larger buffer.
1704 Here is a function which uses @code{regerror}, but always dynamically
1705 allocates a buffer for the error message:
1707 @smallexample
1708 char *get_regerror (int errcode, regex_t *compiled)
1710   size_t length = regerror (errcode, compiled, NULL, 0);
1711   char *buffer = xmalloc (length);
1712   (void) regerror (errcode, compiled, buffer, length);
1713   return buffer;
1715 @end smallexample
1716 @end deftypefun
1718 @node Word Expansion
1719 @section Shell-Style Word Expansion
1720 @cindex word expansion
1721 @cindex expansion of shell words
1723 @dfn{Word expansion} means the process of splitting a string into
1724 @dfn{words} and substituting for variables, commands, and wildcards
1725 just as the shell does.
1727 For example, when you write @samp{ls -l foo.c}, this string is split
1728 into three separate words---@samp{ls}, @samp{-l} and @samp{foo.c}.
1729 This is the most basic function of word expansion.
1731 When you write @samp{ls *.c}, this can become many words, because
1732 the word @samp{*.c} can be replaced with any number of file names.
1733 This is called @dfn{wildcard expansion}, and it is also a part of
1734 word expansion.
1736 When you use @samp{echo $PATH} to print your path, you are taking
1737 advantage of @dfn{variable substitution}, which is also part of word
1738 expansion.
1740 Ordinary programs can perform word expansion just like the shell by
1741 calling the library function @code{wordexp}.
1743 @menu
1744 * Expansion Stages::            What word expansion does to a string.
1745 * Calling Wordexp::             How to call @code{wordexp}.
1746 * Flags for Wordexp::           Options you can enable in @code{wordexp}.
1747 * Wordexp Example::             A sample program that does word expansion.
1748 * Tilde Expansion::             Details of how tilde expansion works.
1749 * Variable Substitution::       Different types of variable substitution.
1750 @end menu
1752 @node Expansion Stages
1753 @subsection The Stages of Word Expansion
1755 When word expansion is applied to a sequence of words, it performs the
1756 following transformations in the order shown here:
1758 @enumerate
1759 @item
1760 @cindex tilde expansion
1761 @dfn{Tilde expansion}: Replacement of @samp{~foo} with the name of
1762 the home directory of @samp{foo}.
1764 @item
1765 Next, three different transformations are applied in the same step,
1766 from left to right:
1768 @itemize @bullet
1769 @item
1770 @cindex variable substitution
1771 @cindex substitution of variables and commands
1772 @dfn{Variable substitution}: Environment variables are substituted for
1773 references such as @samp{$foo}.
1775 @item
1776 @cindex command substitution
1777 @dfn{Command substitution}: Constructs such as @w{@samp{`cat foo`}} and
1778 the equivalent @w{@samp{$(cat foo)}} are replaced with the output from
1779 the inner command.
1781 @item
1782 @cindex arithmetic expansion
1783 @dfn{Arithmetic expansion}: Constructs such as @samp{$(($x-1))} are
1784 replaced with the result of the arithmetic computation.
1785 @end itemize
1787 @item
1788 @cindex field splitting
1789 @dfn{Field splitting}: subdivision of the text into @dfn{words}.
1791 @item
1792 @cindex wildcard expansion
1793 @dfn{Wildcard expansion}: The replacement of a construct such as @samp{*.c}
1794 with a list of @samp{.c} file names.  Wildcard expansion applies to an
1795 entire word at a time, and replaces that word with 0 or more file names
1796 that are themselves words.
1798 @item
1799 @cindex quote removal
1800 @cindex removal of quotes
1801 @dfn{Quote removal}: The deletion of string-quotes, now that they have
1802 done their job by inhibiting the above transformations when appropriate.
1803 @end enumerate
1805 For the details of these transformations, and how to write the constructs
1806 that use them, see @w{@cite{The BASH Manual}} (to appear).
1808 @node Calling Wordexp
1809 @subsection Calling @code{wordexp}
1811 All the functions, constants and data types for word expansion are
1812 declared in the header file @file{wordexp.h}.
1814 Word expansion produces a vector of words (strings).  To return this
1815 vector, @code{wordexp} uses a special data type, @code{wordexp_t}, which
1816 is a structure.  You pass @code{wordexp} the address of the structure,
1817 and it fills in the structure's fields to tell you about the results.
1819 @comment wordexp.h
1820 @comment POSIX.2
1821 @deftp {Data Type} {wordexp_t}
1822 This data type holds a pointer to a word vector.  More precisely, it
1823 records both the address of the word vector and its size.
1825 @table @code
1826 @item we_wordc
1827 The number of elements in the vector.
1829 @item we_wordv
1830 The address of the vector.  This field has type @w{@code{char **}}.
1832 @item we_offs
1833 The offset of the first real element of the vector, from its nominal
1834 address in the @code{we_wordv} field.  Unlike the other fields, this
1835 is always an input to @code{wordexp}, rather than an output from it.
1837 If you use a nonzero offset, then that many elements at the beginning of
1838 the vector are left empty.  (The @code{wordexp} function fills them with
1839 null pointers.)
1841 The @code{we_offs} field is meaningful only if you use the
1842 @code{WRDE_DOOFFS} flag.  Otherwise, the offset is always zero
1843 regardless of what is in this field, and the first real element comes at
1844 the beginning of the vector.
1845 @end table
1846 @end deftp
1848 @comment wordexp.h
1849 @comment POSIX.2
1850 @deftypefun int wordexp (const char *@var{words}, wordexp_t *@var{word-vector-ptr}, int @var{flags})
1851 @safety{@prelim{}@mtunsafe{@mtasurace{:utent} @mtasuconst{:@mtsenv{}} @mtsenv{} @mtascusig{:ALRM} @mtascutimer{} @mtslocale{}}@asunsafe{@ascudlopen{} @ascuplugin{} @ascuintl{} @ascuheap{} @asucorrupt{} @asulock{}}@acunsafe{@acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
1852 @c wordexp @mtasurace:utent @mtasuconst:@mtsenv @mtsenv @mtascusig:ALRM @mtascutimer @mtslocale @ascudlopen @ascuplugin @ascuintl @ascuheap @asucorrupt @asulock @acucorrupt @aculock @acsfd @acsmem
1853 @c  w_newword ok
1854 @c  wordfree dup @asucorrupt @ascuheap @acucorrupt @acsmem
1855 @c  calloc dup @ascuheap @acsmem
1856 @c  getenv dup @mtsenv
1857 @c  strcpy dup ok
1858 @c  parse_backslash @ascuheap @acsmem
1859 @c   w_addchar dup @ascuheap @acsmem
1860 @c  parse_dollars @mtasuconst:@mtsenv @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1861 @c   w_addchar dup @ascuheap @acsmem
1862 @c   parse_arith @mtasuconst:@mtsenv @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1863 @c    w_newword dup ok
1864 @c    parse_dollars dup @mtasuconst:@mtsenv @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1865 @c    parse_backtick dup @ascuplugin @ascuheap @aculock @acsfd @acsmem
1866 @c    parse_qtd_backslash dup @ascuheap @acsmem
1867 @c    eval_expr @mtslocale
1868 @c     eval_expr_multidiv @mtslocale
1869 @c      eval_expr_val @mtslocale
1870 @c       isspace dup @mtslocale
1871 @c       eval_expr dup @mtslocale
1872 @c      isspace dup @mtslocale
1873 @c     isspace dup @mtslocale
1874 @c    free dup @ascuheap @acsmem
1875 @c    w_addchar dup @ascuheap @acsmem
1876 @c    w_addstr dup @ascuheap @acsmem
1877 @c    itoa_word dup ok
1878 @c   parse_comm @ascuplugin @ascuheap @aculock @acsfd @acsmem
1879 @c    w_newword dup ok
1880 @c    pthread_setcancelstate @ascuplugin @ascuheap @acsmem
1881 @c      (disable cancellation around exec_comm; it may do_cancel the
1882 @c       second time, if async cancel is enabled)
1883 @c     THREAD_ATOMIC_CMPXCHG_VAL dup ok
1884 @c     CANCEL_ENABLED_AND_CANCELED_AND_ASYNCHRONOUS dup ok
1885 @c     do_cancel @ascuplugin @ascuheap @acsmem
1886 @c      THREAD_ATOMIC_BIT_SET dup ok
1887 @c      pthread_unwind @ascuplugin @ascuheap @acsmem
1888 @c       Unwind_ForcedUnwind if available @ascuplugin @ascuheap @acsmem
1889 @c       libc_unwind_longjmp otherwise
1890 @c       cleanups
1891 @c    exec_comm @ascuplugin @ascuheap @aculock @acsfd @acsmem
1892 @c     pipe2 dup ok
1893 @c     pipe dup ok
1894 @c     fork dup @ascuplugin @aculock
1895 @c     close dup @acsfd
1896 @c     on child: exec_comm_child -> exec or abort
1897 @c     waitpid dup ok
1898 @c     read dup ok
1899 @c     w_addmem dup @ascuheap @acsmem
1900 @c     strchr dup ok
1901 @c     w_addword dup @ascuheap @acsmem
1902 @c     w_newword dup ok
1903 @c     w_addchar dup @ascuheap @acsmem
1904 @c     free dup @ascuheap @acsmem
1905 @c     kill dup ok
1906 @c    free dup @ascuheap @acsmem
1907 @c   parse_param @mtasuconst:@mtsenv @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1908 @c     reads from __libc_argc and __libc_argv without guards
1909 @c    w_newword dup ok
1910 @c    isalpha dup @mtslocale^^
1911 @c    w_addchar dup @ascuheap @acsmem
1912 @c    isalnum dup @mtslocale^^
1913 @c    isdigit dup @mtslocale^^
1914 @c    strchr dup ok
1915 @c    itoa_word dup ok
1916 @c    atoi dup @mtslocale
1917 @c    getpid dup ok
1918 @c    w_addstr dup @ascuheap @acsmem
1919 @c    free dup @ascuheap @acsmem
1920 @c    strlen dup ok
1921 @c    malloc dup @ascuheap @acsmem
1922 @c    stpcpy dup ok
1923 @c    w_addword dup @ascuheap @acsmem
1924 @c    strdup dup @ascuheap @acsmem
1925 @c    getenv dup @mtsenv
1926 @c    parse_dollars dup @mtasuconst:@mtsenv @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1927 @c    parse_tilde dup @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1928 @c    fnmatch dup @mtsenv @mtslocale @ascuheap @acsmem
1929 @c    mempcpy dup ok
1930 @c    _ dup @ascuintl
1931 @c    fxprintf dup @aculock
1932 @c    setenv dup @mtasuconst:@mtsenv @ascuheap @asulock @acucorrupt @aculock @acsmem
1933 @c    strspn dup ok
1934 @c    strcspn dup ok
1935 @c  parse_backtick @ascuplugin @ascuheap @aculock @acsfd @acsmem
1936 @c   w_newword dup ok
1937 @c   exec_comm dup @ascuplugin @ascuheap @aculock @acsfd @acsmem
1938 @c   free dup @ascuheap @acsmem
1939 @c   parse_qtd_backslash dup @ascuheap @acsmem
1940 @c   parse_backslash dup @ascuheap @acsmem
1941 @c   w_addchar dup @ascuheap @acsmem
1942 @c  parse_dquote @mtasuconst:@mtsenv @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1943 @c   parse_dollars dup @mtasuconst:@mtsenv @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1944 @c   parse_backtick dup @ascuplugin @ascuheap @aculock @acsfd @acsmem
1945 @c   parse_qtd_backslash dup @ascuheap @acsmem
1946 @c   w_addchar dup @ascuheap @acsmem
1947 @c  w_addword dup @ascuheap @acsmem
1948 @c   strdup dup @ascuheap @acsmem
1949 @c   realloc dup @ascuheap @acsmem
1950 @c   free dup @ascuheap @acsmem
1951 @c  parse_squote dup @ascuheap @acsmem
1952 @c   w_addchar dup @ascuheap @acsmem
1953 @c  parse_tilde @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1954 @c   strchr dup ok
1955 @c   w_addchar dup @ascuheap @acsmem
1956 @c   getenv dup @mtsenv
1957 @c   w_addstr dup @ascuheap @acsmem
1958 @c    strlen dup ok
1959 @c    w_addmem dup @ascuheap @acsmem
1960 @c     realloc dup @ascuheap @acsmem
1961 @c     free dup @ascuheap @acsmem
1962 @c     mempcpy dup ok
1963 @c   getuid dup ok
1964 @c   getpwuid_r dup @mtslocale @ascudlopen @ascuplugin @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1965 @c   getpwnam_r dup @mtslocale @ascudlopen @ascuplugin @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1966 @c  parse_glob @mtasurace:utent @mtasuconst:@mtsenv @mtsenv @mtascusig:ALRM @mtascutimer @mtslocale @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1967 @c   strchr dup ok
1968 @c   parse_dollars dup @mtasuconst:@mtsenv @mtslocale @mtsenv @ascudlopen @ascuplugin @ascuintl @ascuheap @asulock @acucorrupt @aculock @acsfd @acsmem
1969 @c   parse_qtd_backslash @ascuheap @acsmem
1970 @c    w_addchar dup @ascuheap @acsmem
1971 @c   parse_backslash dup @ascuheap @acsmem
1972 @c   w_addchar dup @ascuheap @acsmem
1973 @c   w_addword dup @ascuheap @acsmem
1974 @c   w_newword dup ok
1975 @c   do_parse_glob @mtasurace:utent @mtsenv @mtascusig:ALRM @mtascutimer @mtslocale @ascudlopen @ascuplugin @ascuheap @asulock @aculock @acsfd @acsmem
1976 @c    glob dup @mtasurace:utent @mtsenv @mtascusig:ALRM @mtascutimer @mtslocale @ascudlopen @ascuplugin @ascuheap @asulock @aculock @acsfd @acsmem [auto glob_t avoids @asucorrupt @acucorrupt]
1977 @c    w_addstr dup @ascuheap @acsmem
1978 @c    w_addchar dup @ascuheap @acsmem
1979 @c    globfree dup @ascuheap @acsmem [auto glob_t avoids @asucorrupt @acucorrupt]
1980 @c    free dup @ascuheap @acsmem
1981 @c    w_newword dup ok
1982 @c    strdup dup @ascuheap @acsmem
1983 @c    w_addword dup @ascuheap @acsmem
1984 @c   wordfree dup @asucorrupt @ascuheap @acucorrupt @acsmem
1985 @c  strchr dup ok
1986 @c  w_addchar dup @ascuheap @acsmem
1987 @c   realloc dup @ascuheap @acsmem
1988 @c   free dup @ascuheap @acsmem
1989 @c  free dup @ascuheap @acsmem
1990 Perform word expansion on the string @var{words}, putting the result in
1991 a newly allocated vector, and store the size and address of this vector
1992 into @code{*@var{word-vector-ptr}}.  The argument @var{flags} is a
1993 combination of bit flags; see @ref{Flags for Wordexp}, for details of
1994 the flags.
1996 You shouldn't use any of the characters @samp{|&;<>} in the string
1997 @var{words} unless they are quoted; likewise for newline.  If you use
1998 these characters unquoted, you will get the @code{WRDE_BADCHAR} error
1999 code.  Don't use parentheses or braces unless they are quoted or part of
2000 a word expansion construct.  If you use quotation characters @samp{'"`},
2001 they should come in pairs that balance.
2003 The results of word expansion are a sequence of words.  The function
2004 @code{wordexp} allocates a string for each resulting word, then
2005 allocates a vector of type @code{char **} to store the addresses of
2006 these strings.  The last element of the vector is a null pointer.
2007 This vector is called the @dfn{word vector}.
2009 To return this vector, @code{wordexp} stores both its address and its
2010 length (number of elements, not counting the terminating null pointer)
2011 into @code{*@var{word-vector-ptr}}.
2013 If @code{wordexp} succeeds, it returns 0.  Otherwise, it returns one
2014 of these error codes:
2016 @table @code
2017 @comment wordexp.h
2018 @comment POSIX.2
2019 @item WRDE_BADCHAR
2020 The input string @var{words} contains an unquoted invalid character such
2021 as @samp{|}.
2023 @comment wordexp.h
2024 @comment POSIX.2
2025 @item WRDE_BADVAL
2026 The input string refers to an undefined shell variable, and you used the flag
2027 @code{WRDE_UNDEF} to forbid such references.
2029 @comment wordexp.h
2030 @comment POSIX.2
2031 @item WRDE_CMDSUB
2032 The input string uses command substitution, and you used the flag
2033 @code{WRDE_NOCMD} to forbid command substitution.
2035 @comment wordexp.h
2036 @comment POSIX.2
2037 @item WRDE_NOSPACE
2038 It was impossible to allocate memory to hold the result.  In this case,
2039 @code{wordexp} can store part of the results---as much as it could
2040 allocate room for.
2042 @comment wordexp.h
2043 @comment POSIX.2
2044 @item WRDE_SYNTAX
2045 There was a syntax error in the input string.  For example, an unmatched
2046 quoting character is a syntax error.  This error code is also used to
2047 signal division by zero and overflow in arithmetic expansion.
2048 @end table
2049 @end deftypefun
2051 @comment wordexp.h
2052 @comment POSIX.2
2053 @deftypefun void wordfree (wordexp_t *@var{word-vector-ptr})
2054 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
2055 @c wordfree dup @asucorrupt @ascuheap @acucorrupt @acsmem
2056 @c  free dup @ascuheap @acsmem
2057 Free the storage used for the word-strings and vector that
2058 @code{*@var{word-vector-ptr}} points to.  This does not free the
2059 structure @code{*@var{word-vector-ptr}} itself---only the other
2060 data it points to.
2061 @end deftypefun
2063 @node Flags for Wordexp
2064 @subsection Flags for Word Expansion
2066 This section describes the flags that you can specify in the
2067 @var{flags} argument to @code{wordexp}.  Choose the flags you want,
2068 and combine them with the C operator @code{|}.
2070 @table @code
2071 @comment wordexp.h
2072 @comment POSIX.2
2073 @item WRDE_APPEND
2074 Append the words from this expansion to the vector of words produced by
2075 previous calls to @code{wordexp}.  This way you can effectively expand
2076 several words as if they were concatenated with spaces between them.
2078 In order for appending to work, you must not modify the contents of the
2079 word vector structure between calls to @code{wordexp}.  And, if you set
2080 @code{WRDE_DOOFFS} in the first call to @code{wordexp}, you must also
2081 set it when you append to the results.
2083 @comment wordexp.h
2084 @comment POSIX.2
2085 @item WRDE_DOOFFS
2086 Leave blank slots at the beginning of the vector of words.
2087 The @code{we_offs} field says how many slots to leave.
2088 The blank slots contain null pointers.
2090 @comment wordexp.h
2091 @comment POSIX.2
2092 @item WRDE_NOCMD
2093 Don't do command substitution; if the input requests command substitution,
2094 report an error.
2096 @comment wordexp.h
2097 @comment POSIX.2
2098 @item WRDE_REUSE
2099 Reuse a word vector made by a previous call to @code{wordexp}.
2100 Instead of allocating a new vector of words, this call to @code{wordexp}
2101 will use the vector that already exists (making it larger if necessary).
2103 Note that the vector may move, so it is not safe to save an old pointer
2104 and use it again after calling @code{wordexp}.  You must fetch
2105 @code{we_pathv} anew after each call.
2107 @comment wordexp.h
2108 @comment POSIX.2
2109 @item WRDE_SHOWERR
2110 Do show any error messages printed by commands run by command substitution.
2111 More precisely, allow these commands to inherit the standard error output
2112 stream of the current process.  By default, @code{wordexp} gives these
2113 commands a standard error stream that discards all output.
2115 @comment wordexp.h
2116 @comment POSIX.2
2117 @item WRDE_UNDEF
2118 If the input refers to a shell variable that is not defined, report an
2119 error.
2120 @end table
2122 @node Wordexp Example
2123 @subsection @code{wordexp} Example
2125 Here is an example of using @code{wordexp} to expand several strings
2126 and use the results to run a shell command.  It also shows the use of
2127 @code{WRDE_APPEND} to concatenate the expansions and of @code{wordfree}
2128 to free the space allocated by @code{wordexp}.
2130 @smallexample
2132 expand_and_execute (const char *program, const char **options)
2134   wordexp_t result;
2135   pid_t pid
2136   int status, i;
2138   /* @r{Expand the string for the program to run.}  */
2139   switch (wordexp (program, &result, 0))
2140     @{
2141     case 0:                     /* @r{Successful}.  */
2142       break;
2143     case WRDE_NOSPACE:
2144       /* @r{If the error was @code{WRDE_NOSPACE},}
2145          @r{then perhaps part of the result was allocated.}  */
2146       wordfree (&result);
2147     default:                    /* @r{Some other error.}  */
2148       return -1;
2149     @}
2151   /* @r{Expand the strings specified for the arguments.}  */
2152   for (i = 0; options[i] != NULL; i++)
2153     @{
2154       if (wordexp (options[i], &result, WRDE_APPEND))
2155         @{
2156           wordfree (&result);
2157           return -1;
2158         @}
2159     @}
2161   pid = fork ();
2162   if (pid == 0)
2163     @{
2164       /* @r{This is the child process.  Execute the command.} */
2165       execv (result.we_wordv[0], result.we_wordv);
2166       exit (EXIT_FAILURE);
2167     @}
2168   else if (pid < 0)
2169     /* @r{The fork failed.  Report failure.}  */
2170     status = -1;
2171   else
2172     /* @r{This is the parent process.  Wait for the child to complete.}  */
2173     if (waitpid (pid, &status, 0) != pid)
2174       status = -1;
2176   wordfree (&result);
2177   return status;
2179 @end smallexample
2181 @node Tilde Expansion
2182 @subsection Details of Tilde Expansion
2184 It's a standard part of shell syntax that you can use @samp{~} at the
2185 beginning of a file name to stand for your own home directory.  You
2186 can use @samp{~@var{user}} to stand for @var{user}'s home directory.
2188 @dfn{Tilde expansion} is the process of converting these abbreviations
2189 to the directory names that they stand for.
2191 Tilde expansion applies to the @samp{~} plus all following characters up
2192 to whitespace or a slash.  It takes place only at the beginning of a
2193 word, and only if none of the characters to be transformed is quoted in
2194 any way.
2196 Plain @samp{~} uses the value of the environment variable @code{HOME}
2197 as the proper home directory name.  @samp{~} followed by a user name
2198 uses @code{getpwname} to look up that user in the user database, and
2199 uses whatever directory is recorded there.  Thus, @samp{~} followed
2200 by your own name can give different results from plain @samp{~}, if
2201 the value of @code{HOME} is not really your home directory.
2203 @node Variable Substitution
2204 @subsection Details of Variable Substitution
2206 Part of ordinary shell syntax is the use of @samp{$@var{variable}} to
2207 substitute the value of a shell variable into a command.  This is called
2208 @dfn{variable substitution}, and it is one part of doing word expansion.
2210 There are two basic ways you can write a variable reference for
2211 substitution:
2213 @table @code
2214 @item $@{@var{variable}@}
2215 If you write braces around the variable name, then it is completely
2216 unambiguous where the variable name ends.  You can concatenate
2217 additional letters onto the end of the variable value by writing them
2218 immediately after the close brace.  For example, @samp{$@{foo@}s}
2219 expands into @samp{tractors}.
2221 @item $@var{variable}
2222 If you do not put braces around the variable name, then the variable
2223 name consists of all the alphanumeric characters and underscores that
2224 follow the @samp{$}.  The next punctuation character ends the variable
2225 name.  Thus, @samp{$foo-bar} refers to the variable @code{foo} and expands
2226 into @samp{tractor-bar}.
2227 @end table
2229 When you use braces, you can also use various constructs to modify the
2230 value that is substituted, or test it in various ways.
2232 @table @code
2233 @item $@{@var{variable}:-@var{default}@}
2234 Substitute the value of @var{variable}, but if that is empty or
2235 undefined, use @var{default} instead.
2237 @item $@{@var{variable}:=@var{default}@}
2238 Substitute the value of @var{variable}, but if that is empty or
2239 undefined, use @var{default} instead and set the variable to
2240 @var{default}.
2242 @item $@{@var{variable}:?@var{message}@}
2243 If @var{variable} is defined and not empty, substitute its value.
2245 Otherwise, print @var{message} as an error message on the standard error
2246 stream, and consider word expansion a failure.
2248 @c ??? How does wordexp report such an error?
2249 @c WRDE_BADVAL is returned.
2251 @item $@{@var{variable}:+@var{replacement}@}
2252 Substitute @var{replacement}, but only if @var{variable} is defined and
2253 nonempty.  Otherwise, substitute nothing for this construct.
2254 @end table
2256 @table @code
2257 @item $@{#@var{variable}@}
2258 Substitute a numeral which expresses in base ten the number of
2259 characters in the value of @var{variable}.  @samp{$@{#foo@}} stands for
2260 @samp{7}, because @samp{tractor} is seven characters.
2261 @end table
2263 These variants of variable substitution let you remove part of the
2264 variable's value before substituting it.  The @var{prefix} and
2265 @var{suffix} are not mere strings; they are wildcard patterns, just
2266 like the patterns that you use to match multiple file names.  But
2267 in this context, they match against parts of the variable value
2268 rather than against file names.
2270 @table @code
2271 @item $@{@var{variable}%%@var{suffix}@}
2272 Substitute the value of @var{variable}, but first discard from that
2273 variable any portion at the end that matches the pattern @var{suffix}.
2275 If there is more than one alternative for how to match against
2276 @var{suffix}, this construct uses the longest possible match.
2278 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
2279 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
2281 @item $@{@var{variable}%@var{suffix}@}
2282 Substitute the value of @var{variable}, but first discard from that
2283 variable any portion at the end that matches the pattern @var{suffix}.
2285 If there is more than one alternative for how to match against
2286 @var{suffix}, this construct uses the shortest possible alternative.
2288 Thus, @samp{$@{foo%r*@}} substitutes @samp{tracto}, because the shortest
2289 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
2291 @item $@{@var{variable}##@var{prefix}@}
2292 Substitute the value of @var{variable}, but first discard from that
2293 variable any portion at the beginning that matches the pattern @var{prefix}.
2295 If there is more than one alternative for how to match against
2296 @var{prefix}, this construct uses the longest possible match.
2298 Thus, @samp{$@{foo##*t@}} substitutes @samp{or}, because the largest
2299 match for @samp{*t} at the beginning of @samp{tractor} is @samp{tract}.
2301 @item $@{@var{variable}#@var{prefix}@}
2302 Substitute the value of @var{variable}, but first discard from that
2303 variable any portion at the beginning that matches the pattern @var{prefix}.
2305 If there is more than one alternative for how to match against
2306 @var{prefix}, this construct uses the shortest possible alternative.
2308 Thus, @samp{$@{foo#*t@}} substitutes @samp{ractor}, because the shortest
2309 match for @samp{*t} at the beginning of @samp{tractor} is just @samp{t}.
2311 @end table