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 // This is a limitation of lyx::regex, but all other chars in BREs
20 // are assumed literal.
21 lyx::regex reg("[].|*?+(){}^$\\[\\\\]");
23 // $& is a perl-like expression that expands to all
24 // of the current match
25 // The '$' must be prefixed with the escape character '\' for
26 // boost to treat it as a literal.
27 // Thus, to prefix a matched expression with '\', we use:
28 return lyx::regex_replace(expr, reg, "\\\\$&");
32 typedef map<string, string> InfoMap;
34 // A functor for use with find_if, used to ascertain whether a
35 // data entry matches the required regex_
36 // This class is unfortunately copied from ../frontend_helpers.cpp, so we should
37 // try to make sure to keep the two in sync.
38 class RegexMatch : public unary_function<string, bool>
41 // re is used to construct an instance of lyx::regex.
42 RegexMatch(InfoMap const & m, string const & re)
43 : map_(m), regex_(re) {}
45 bool operator()(string const & key) const {
46 // the data searched is the key + its associated BibTeX/biblio
49 InfoMap::const_iterator info = map_.find(key);
50 if (info != map_.end())
51 data += ' ' + info->second;
53 // Attempts to find a match for the current RE
55 return lyx::regex_search(data, regex_);
59 mutable lyx::regex regex_;
63 void test_escape_special_chars()
65 cout << escape_special_chars("abcd") << endl;
66 cout << escape_special_chars("ab&cd") << endl;
67 cout << escape_special_chars(".|*?+(){}[]^$\"") << endl;
68 cout << escape_special_chars("..||**??++(()){{}}[[]]^^$$\\\\") << endl;
72 void test_RegexMatch()
78 RegexMatch rm(im, "h.*o");
80 cout << rm("hello") << endl;
81 cout << rm("hei") << endl;
83 catch (lyx::regex_error & regerr) {
84 cout << regerr.what() << endl;
91 test_escape_special_chars();