From 464a58402422d59643e2b882a4373185d6b00ed3 Mon Sep 17 00:00:00 2001 From: Rachel Heaton Date: Tue, 4 Aug 2020 17:14:27 -0600 Subject: [PATCH 1/2] Add support for regex.QuoteMeta string conversion --- docs/strings.md | 11 +++++++++++ regex.go | 4 ++++ regex_test.go | 5 +++++ 3 files changed, 20 insertions(+) diff --git a/docs/strings.md b/docs/strings.md index a4ae813e..2e0f455d 100644 --- a/docs/strings.md +++ b/docs/strings.md @@ -446,6 +446,17 @@ The above produces `[pi a]` `regexSplit` panics if there is a problem and `mustRegexSplit` returns an error to the template engine if there is a problem. +## regexQuoteMeta + +Returns a string that escapes all regular expression metacharacters inside the argument text; +the returned string is a regular expression matching the literal text. + +``` +regexQuoteMeta "1.2.3" +``` + +The above produces `1\.2\.3` + ## See Also... The [Conversion Functions](conversion.html) contain functions for converting diff --git a/regex.go b/regex.go index 2370878f..fab55101 100644 --- a/regex.go +++ b/regex.go @@ -77,3 +77,7 @@ func mustRegexSplit(regex string, s string, n int) ([]string, error) { } return r.Split(s, n), nil } + +func regexQuoteMeta(s string) string { + return regexp.QuoteMeta(s) +} diff --git a/regex_test.go b/regex_test.go index 70daf9c3..60aafc29 100644 --- a/regex_test.go +++ b/regex_test.go @@ -196,3 +196,8 @@ func TestMustRegexSplit(t *testing.T) { assert.Equal(t, c.expected, len(res), "case %#v", c.args) } } + +func TestRegexQuoteMeta(t *testing.T) { + assert.Equal(t, "1\\.2\\.3", regexQuoteMeta("1.2.3")) + assert.Equal(t, "pretzel", regexQuoteMeta("pretzel")) +} From 1c12b853b2188c5f741583d571929121bb7fc27a Mon Sep 17 00:00:00 2001 From: Rachel Heaton Date: Tue, 4 Aug 2020 19:29:12 -0600 Subject: [PATCH 2/2] Add regexQuoteMeta to function map --- functions.go | 1 + functions_test.go | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/functions.go b/functions.go index c16e9c3e..51df34c5 100644 --- a/functions.go +++ b/functions.go @@ -332,6 +332,7 @@ var genericMap = map[string]interface{}{ "mustRegexReplaceAllLiteral": mustRegexReplaceAllLiteral, "regexSplit": regexSplit, "mustRegexSplit": mustRegexSplit, + "regexQuoteMeta": regexQuoteMeta, // URLs: "urlParse": urlParse, diff --git a/functions_test.go b/functions_test.go index 737458c8..e06c8f6a 100644 --- a/functions_test.go +++ b/functions_test.go @@ -82,6 +82,11 @@ func TestShuffle(t *testing.T) { assert.NoError(t, runt(`{{ shuffle "Hello World" }}`, "rldo HWlloe")) } +func TestRegex(t *testing.T) { + assert.NoError(t, runt(`{{ regexQuoteMeta "1.2.3" }}`, "1\\.2\\.3")) + assert.NoError(t, runt(`{{ regexQuoteMeta "pretzel" }}`, "pretzel")) +} + // runt runs a template and checks that the output exactly matches the expected string. func runt(tpl, expect string) error { return runtv(tpl, expect, map[string]string{})