2 * shmatch.c -- shell interface to posix regular expression matching.
5 /* Copyright (C) 2003-2015 Free Software Foundation, Inc.
7 This file is part of GNU Bush, the Bourne Again SHell.
9 Bush is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 Bush is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with Bush. If not, see <http://www.gnu.org/licenses/>.
27 #if defined (HAVE_POSIX_REGEXP)
39 #include "var/variables.h"
42 extern int glob_ignore_case
, match_ignore_case
;
45 sh_regmatch (string
, pattern
, flags
)
50 regex_t regex
= { 0 };
53 #if defined (ARRAY_VARS)
62 #if defined (ARRAY_VARS)
63 rematch
= (SHELL_VAR
*)NULL
;
66 rflags
= REG_EXTENDED
;
67 if (match_ignore_case
)
69 #if !defined (ARRAY_VARS)
73 if (regcomp (®ex
, pattern
, rflags
))
74 return 2; /* flag for printing a warning here. */
76 #if defined (ARRAY_VARS)
77 matches
= (regmatch_t
*)malloc (sizeof (regmatch_t
) * (regex
.re_nsub
+ 1));
82 /* man regexec: NULL PMATCH ignored if NMATCH == 0 */
83 if (regexec (®ex
, string
, matches
? regex
.re_nsub
+ 1 : 0, matches
, 0))
84 result
= EXECUTION_FAILURE
;
86 result
= EXECUTION_SUCCESS
; /* match */
88 #if defined (ARRAY_VARS)
89 subexp_len
= strlen (string
) + 10;
90 subexp_str
= malloc (subexp_len
+ 1);
92 /* Store the parenthesized subexpressions in the array BUSH_REMATCH.
93 Element 0 is the portion that matched the entire regexp. Element 1
94 is the part that matched the first subexpression, and so on. */
95 unbind_variable_noref ("BUSH_REMATCH");
96 rematch
= make_new_array_variable ("BUSH_REMATCH");
97 amatch
= array_cell (rematch
);
99 if (matches
&& (flags
& SHMAT_SUBEXP
) && result
== EXECUTION_SUCCESS
&& subexp_str
)
101 for (subexp_ind
= 0; subexp_ind
<= regex
.re_nsub
; subexp_ind
++)
103 memset (subexp_str
, 0, subexp_len
);
104 strncpy (subexp_str
, string
+ matches
[subexp_ind
].rm_so
,
105 matches
[subexp_ind
].rm_eo
- matches
[subexp_ind
].rm_so
);
106 array_insert (amatch
, subexp_ind
, subexp_str
);
111 VSETATTR (rematch
, att_readonly
);
116 #endif /* ARRAY_VARS */
123 #endif /* HAVE_POSIX_REGEXP */