Boost logo

Boost :

Subject: Re: [boost] [regex] embed string/char in regex w/o escaping?
From: John Maddock (boost.regex_at_[hidden])
Date: 2011-03-02 04:29:19


>As far as I can see, there is no way to embed a plain string into a regex,
>without escaping the string. Same with characters.
>Isn't that a bad omission for a library that becomes the new C++ standard?
>Escaping something just to unescape it on the
>other end of the function call seems unnecessary, and it opens up the
>possibility of ills like regex code injection if someone
>forgets to escape or does it wrong.

Good question - if this is Boost.Regex rather than the std then there is an
option to treat a whole string as a literal (as Jim Bell mentioned), or you
can enclose part of a string that has to be treated as a literal in \Q...\E
as in Perl.

Otherwise you're looking at a call to regex_replace to quote things for you,
off the top of my head something like:

regex e("[.\[\]{}()\\\\*+?|^$]");
std::string my_escaped_string = "(?:" + regex_replace(my_string, e,
"\\\\$&") + ")";

Should do the trick.

HTH, John.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk