Bug 2104 – std.regex: escape function for regular expressions
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
All
Creation time
2008-05-13T04:17:00Z
Last change time
2016-04-14T15:53:05Z
Keywords
pull
Assigned to
dmitry.olsh
Creator
gaboonviper
Comments
Comment #0 by gaboonviper — 2008-05-13T04:17:09Z
I've been using regular expressions extensively and found that there was no escape function in the std.regexp library. It's useful when using user input in regular expressions.
Here's a simple one I built. It's probably not the most efficient one out there, but feel free to use it.
string regEscape(string aExpression)
{
return sub(aExpression, r"[\\\.\*\+\?\^\$\[\]\{\}\(\)\|]", "\\$&", "g");
}
Usage:
string needle1 = r"[needle]";
string needle2 = r"(needle)";
string haystack = r"[needle] (needle)";
// find needles 1 and/or 2 in the haystack
auto result = RegExp(regEscape(needle1) ~ "|" ~ regEscape(needle2)).search(haystack);
Cheers,
Boyd