6 #include "support/regex.h"
10 // Escape special chars.
11 // All characters are literals except: '.|*?+(){}[]^$\'
12 // These characters are literals when preceded by a "\", which is done here
13 // This function is unfortunately copied from ../qt4/GuiCitation.cpp, so we
14 // should try to make sure to keep the two in sync.
15 string const escape_special_chars(string const & expr)
17 // Search for all chars '.|*?+(){}[^$]\'
18 // Note that '[', ']', and '\' must be escaped.
19 lyx::regex reg("[.|*?+(){}^$\\[\\]\\\\]");
21 // $& is a ECMAScript format expression that expands to all
22 // of the current match
23 #ifdef LYX_USE_STD_REGEX
24 // To prefix a matched expression with a single literal backslash, we
25 // need to escape it for the C++ compiler and use:
26 return lyx::regex_replace(expr, reg, "\\$&");
28 // A backslash in the format string starts an escape sequence in boost.
29 // Thus, to prefix a matched expression with a single literal backslash,
30 // we need to give two backslashes to the regex engine, and escape both
31 // for the C++ compiler and use:
32 return lyx::regex_replace(expr, reg, "\\\\$&");
37 typedef map<string, string> InfoMap;
39 // A functor for use with find_if, used to ascertain whether a
40 // data entry matches the required regex_
41 // This class is unfortunately copied from ../frontend_helpers.cpp, so we should
42 // try to make sure to keep the two in sync.
43 class RegexMatch : public unary_function<string, bool>
46 // re is used to construct an instance of lyx::regex.
47 RegexMatch(InfoMap const & m, string const & re)
48 : map_(m), regex_(re) {}
50 bool operator()(string const & key) const {
51 // the data searched is the key + its associated BibTeX/biblio
54 InfoMap::const_iterator info = map_.find(key);
55 if (info != map_.end())
56 data += ' ' + info->second;
58 // Attempts to find a match for the current RE
60 return lyx::regex_search(data, regex_);
64 mutable lyx::regex regex_;
68 void test_escape_special_chars()
70 cout << escape_special_chars("abcd") << endl;
71 cout << escape_special_chars("ab&cd") << endl;
72 cout << escape_special_chars(".|*?+(){}[]^$\"") << endl;
73 cout << escape_special_chars("..||**??++(()){{}}[[]]^^$$\\\\") << endl;
77 void test_RegexMatch()
83 RegexMatch rm(im, "h.*o");
85 cout << rm("hello") << endl;
86 cout << rm("hei") << endl;
88 catch (lyx::regex_error & regerr) {
89 cout << regerr.what() << endl;
96 test_escape_special_chars();