Skip to content

Commit

Permalink
Add support for regex.QuoteMeta string conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
Rachel Heaton committed Aug 4, 2020
1 parent 4241ae8 commit 3e65f69
Show file tree
Hide file tree
Showing 3 changed files with 20 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
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 3e65f69

Please sign in to comment.