Skip to content

Commit

Permalink
Merge pull request #257 from rheaton/master
Browse files Browse the repository at this point in the history
Signed-off-by: Matt Farina <matt@mattfarina.com>
  • Loading branch information
mattfarina authored Dec 2, 2020
2 parents ef25c39 + 1c12b85 commit 37818c4
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 0 deletions.
11 changes: 11 additions & 0 deletions docs/strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ var genericMap = map[string]interface{}{
"mustRegexReplaceAllLiteral": mustRegexReplaceAllLiteral,
"regexSplit": regexSplit,
"mustRegexSplit": mustRegexSplit,
"regexQuoteMeta": regexQuoteMeta,

// URLs:
"urlParse": urlParse,
Expand Down
5 changes: 5 additions & 0 deletions functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,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{})
Expand Down
4 changes: 4 additions & 0 deletions regex.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
5 changes: 5 additions & 0 deletions regex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}

0 comments on commit 37818c4

Please sign in to comment.