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 // The '$' must be prefixed with the escape character '\' for
24 // boost to treat it as a literal.
25 // Thus, to prefix a matched expression with '\', we use:
26 return lyx::regex_replace(expr, reg, "\\\\$&");
30 typedef map<string, string> InfoMap;
32 // A functor for use with find_if, used to ascertain whether a
33 // data entry matches the required regex_
34 // This class is unfortunately copied from ../frontend_helpers.cpp, so we should
35 // try to make sure to keep the two in sync.
36 class RegexMatch : public unary_function<string, bool>
39 // re is used to construct an instance of lyx::regex.
40 RegexMatch(InfoMap const & m, string const & re)
41 : map_(m), regex_(re) {}
43 bool operator()(string const & key) const {
44 // the data searched is the key + its associated BibTeX/biblio
47 InfoMap::const_iterator info = map_.find(key);
48 if (info != map_.end())
49 data += ' ' + info->second;
51 // Attempts to find a match for the current RE
53 return lyx::regex_search(data, regex_);
57 mutable lyx::regex regex_;
61 void test_escape_special_chars()
63 cout << escape_special_chars("abcd") << endl;
64 cout << escape_special_chars("ab&cd") << endl;
65 cout << escape_special_chars(".|*?+(){}[]^$\"") << endl;
66 cout << escape_special_chars("..||**??++(()){{}}[[]]^^$$\\\\") << endl;
70 void test_RegexMatch()
76 RegexMatch rm(im, "h.*o");
78 cout << rm("hello") << endl;
79 cout << rm("hei") << endl;
81 catch (lyx::regex_error & regerr) {
82 cout << regerr.what() << endl;
89 test_escape_special_chars();