Line data Source code
1 : // Copyright (c) 2021-2025 Made to Order Software Corp. All Rights Reserved
2 : //
3 : // https://snapwebsites.org/project/snapdev
4 : // contact@m2osw.com
5 : //
6 : // This program is free software: you can redistribute it and/or modify
7 : // it under the terms of the GNU General Public License as published by
8 : // the Free Software Foundation, either version 3 of the License, or
9 : // (at your option) any later version.
10 : //
11 : // This program is distributed in the hope that it will be useful,
12 : // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 : // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 : // GNU General Public License for more details.
15 : //
16 : // You should have received a copy of the GNU General Public License
17 : // along with this program. If not, see <https://www.gnu.org/licenses/>.
18 :
19 : /** \file
20 : * \brief Verify the escaping of regex special characters.
21 : *
22 : * At times you want to build a regular expression dynamically with parts
23 : * of the expression including user entered characters. Those character
24 : * usually need to be escaped to work properly in a regular expression.
25 : * For example, the period (.) character has a special meaning in a
26 : * regular expression (usually, all character except '\\n' or \\r').
27 : * For that character to represent a period in the source string of
28 : * the regular expression, it needs to be escaped (preceded by a
29 : * backslash character). This function does that on all the regular
30 : * expression characters.
31 : *
32 : * This file implements tests to verify that all the special characters
33 : * are indeed escaped.
34 : */
35 :
36 : // self
37 : //
38 : #include <snapdev/escape_special_regex_characters.h>
39 :
40 : #include "catch_main.h"
41 :
42 :
43 :
44 : // last include
45 : //
46 : #include <snapdev/poison.h>
47 :
48 :
49 :
50 : namespace
51 : {
52 :
53 :
54 :
55 :
56 :
57 : } // no name namespace
58 :
59 :
60 :
61 1 : CATCH_TEST_CASE("escape_special_regex_characters", "[regex][string]")
62 : {
63 1 : CATCH_START_SECTION("escape_special_regex_characters: verify that all special characters are indeed escaped")
64 : {
65 1 : char const special_characters[] = {
66 : '$',
67 : '(',
68 : ')',
69 : '*',
70 : '+',
71 : '.',
72 : '/',
73 : '?',
74 : '[',
75 : '\\',
76 : ']',
77 : '^',
78 : '{',
79 : '|',
80 : '}',
81 : '\0',
82 : };
83 :
84 1 : int pos(0);
85 128 : for(int c(1); c < 128; ++c)
86 : {
87 381 : std::string const in(1, static_cast<char>(c));
88 127 : std::string const out(snapdev::escape_special_regex_characters(in));
89 127 : if(c == special_characters[pos])
90 : {
91 15 : std::string const expected('\\' + in);
92 15 : CATCH_REQUIRE(expected == out);
93 15 : ++pos;
94 15 : }
95 : else
96 : {
97 112 : CATCH_REQUIRE(in == out);
98 : }
99 127 : }
100 : }
101 1 : CATCH_END_SECTION()
102 1 : }
103 :
104 :
105 :
106 : // vim: ts=4 sw=4 et
|