Add format_string::escape

This produces a string where all format string characters have been properly escaped.
This commit is contained in:
Allan Odgaard
2012-08-24 21:42:20 +02:00
parent fbfc42be34
commit 13026c70ca
3 changed files with 41 additions and 0 deletions

View File

@@ -296,6 +296,32 @@ namespace format_string
return format_string_t(format).expand(variables);
}
std::string escape (std::string const& format)
{
std::string res = "";
for(size_t i = 0; i < format.size(); ++i)
{
switch(format[i])
{
case '\t': res.append("\\t"); break;
case '\r': res.append("\\r"); break;
case '\n': res.append("\\n"); break;
case '$': case '(': case '\\':
{
if(format[i] != '\\' || i+1 != format.size() && strchr("\\$(trn", format[i+1]))
res.append("\\");
}
/* continue */
default:
res += format[i];
break;
}
}
return res;
}
} /* format_string */
namespace snippet

View File

@@ -29,6 +29,7 @@ namespace format_string
PUBLIC std::string replace (std::string const& src, regexp::pattern_t const& ptrn, format_string_t const& format, bool repeat = true, string_map_t const& variables = string_map_t());
PUBLIC std::string expand (std::string const& format, string_map_t const& variables = string_map_t());
PUBLIC std::string escape (std::string const& format);
} /* format_string */

View File

@@ -24,4 +24,18 @@ public:
TS_ASSERT_EQUALS(replace("foo bar", "(foo)? bar", "(?n:baz)"), "(?n:baz)");
TS_ASSERT_EQUALS(replace("foo bar", "(foo)? bar", "(?n:baz:)"), "(?n:baz:)");
}
void test_escape_format_string ()
{
using format_string::escape;
using format_string::expand;
TS_ASSERT_EQUALS(escape("\t\n\r\\q"), "\\t\\n\\r\\q");
TS_ASSERT_EQUALS(expand(escape("${var}")), "${var}");
TS_ASSERT_EQUALS(expand(escape("foo\n")), "foo\n");
TS_ASSERT_EQUALS(expand(escape("foo\\n")), "foo\\n");
TS_ASSERT_EQUALS(expand(escape("\\No-Escape")), "\\No-Escape");
TS_ASSERT_EQUALS(expand(escape("(?bla)")), "(?bla)");
TS_ASSERT_EQUALS(expand(escape("Escape\\\\me")), "Escape\\\\me");
TS_ASSERT_EQUALS(expand(escape("(?1:baz: buz)")), "(?1:baz: buz)");
}
};