1 /* Construct a regular expression from a literal string.
2 Copyright (C) 1995, 2010 Free Software Foundation, Inc.
3 Written by Bruno Haible <haible@clisp.cons.org>, 2010.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "regex-quote.h"
28 /* Characters that are special in a BRE. */
29 static const char bre_special[] = "$^.*[]\\";
31 /* Characters that are special in an ERE. */
32 static const char ere_special[] = "$^.*[]\\+?()";
35 regex_quote_length (const char *string, int cflags)
37 const char *special = (cflags != 0 ? ere_special : bre_special);
42 for (mbui_init (iter, string); mbui_avail (iter); mbui_advance (iter))
44 /* We know that special contains only ASCII characters. */
45 if (mb_len (mbui_cur (iter)) == 1
46 && strchr (special, * mbui_cur_ptr (iter)))
48 length += mb_len (mbui_cur (iter));
53 /* Copies the quoted string to p and returns the incremented p.
54 There must be room for regex_quote_length (string, cflags) + 1 bytes at p.
57 regex_quote_copy (char *p, const char *string, int cflags)
59 const char *special = (cflags != 0 ? ere_special : bre_special);
62 for (mbui_init (iter, string); mbui_avail (iter); mbui_advance (iter))
64 /* We know that special contains only ASCII characters. */
65 if (mb_len (mbui_cur (iter)) == 1
66 && strchr (special, * mbui_cur_ptr (iter)))
68 memcpy (p, mbui_cur_ptr (iter), mb_len (mbui_cur (iter)));
69 p += mb_len (mbui_cur (iter));
74 /* Returns the freshly allocated quoted string. */
76 regex_quote (const char *string, int cflags)
78 size_t length = regex_quote_length (string, cflags);
79 char *result = XNMALLOC (length + 1, char);
83 p = regex_quote_copy (p, string, cflags);