6 #include <boost/regex.hpp>
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 ../frontend_helpers.cpp, so we should
14 // 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 boost::regex, but all other chars in BREs
20 // are assumed literal.
21 boost::regex reg("[].|*?+(){}^$\\[\\\\]");
23 // $& is a perl-like expression that expands to all of the current match
24 // The '$' must be prefixed with the escape character '\' for
25 // boost to treat it as a literal.
26 // Thus, to prefix a matched expression with '\', we use:
27 return boost::regex_replace(expr, reg, "\\\\$&");
31 typedef map<string, string> InfoMap;
33 // A functor for use with find_if, used to ascertain whether a
34 // data entry matches the required regex_
35 // This class is unfortunately copied from ../frontend_helpers.cpp, so we should
36 // try to make sure to keep the two in sync.
37 class RegexMatch : public unary_function<string, bool>
40 // re and icase are used to construct an instance of boost::RegEx.
41 // if icase is true, then matching is insensitive to case
42 RegexMatch(InfoMap const & m, string const & re, bool icase)
43 : map_(m), regex_(re, icase) {}
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 boost::regex_search(data, regex_);
59 mutable boost::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", false);
80 cout << rm("hello") << endl;
81 cout << rm("hei") << endl;
83 catch (boost::regex_error & regerr) {
84 cout << regerr.what() << endl;
91 test_escape_special_chars();