Regexp

The Regexp registry includes functions for pattern matching and string manipulation using regular expressions, providing powerful text processing capabilities.

You can easily import all the functions from the regexp registry by including the following import statement in your code

import "github.com/go-sprout/sprout/registry/regexp"

regexFind

The function returns the first match found in the string that corresponds to the specified regular expression pattern.

Signature

RegexFind(regex string, s string) (string, error)
{{ "hello world" | regexFind "hello" }} // Output: "hello", nil
{{ "hello world" | regexFind "\invalid$^///" }} // Error

regexFindAll

The function returns all matches of the regex pattern in the string, up to a specified maximum number of matches (n).

Signature

RegexFindAll(regex string, s string, n int) ([]string, error)
{{ regexFindAll "a.", "aba acada afa", 3 }} // Output: ["ab", "ac", "af"], nil
{{ regexFindAll "\invalid$^///", "aba acada afa", 3 }} // Error

regexMatch

The function checks if the entire string matches the given regular expression pattern.

Signature

RegexMatch(regex string, s string) (bool, error)
{{ regexMatch "^[a-zA-Z]+$", "Hello" }} // Output: true, nil
{{ regexMatch "\invalid$^///", "Hello" }} // Output: false, error

regexSplit

The function splits the string into substrings based on matches of the regex pattern, performing the split up to n times.

Signature

RegexSplit(regex string, s string, n int) ([]string, error)
{{ mustRegexSplit "\\s+", "hello world from Go", 2 }} // Output: ["hello", "world from Go"], nil
{{ mustRegexSplit "\invalid$^///", "hello world from Go", 2 }} // Error

regexReplaceAll

The function replaces all occurrences of the regex pattern in the string with the specified replacement string.

Signature

RegexReplaceAll(regex string, s string, repl string) (string, error)
{{ regexReplaceAll "\\d", "R2D2 C3PO", "X" }} // Output: "RXDX CXPO", nil
{{ regexReplaceAll "\invalid$^///", "R2D2 C3PO", "X" }} // Output: "", error

regexReplaceAllLiteral

The function replaces all occurrences of the regex pattern in the string with the specified literal replacement string, without interpreting any special characters in the replacement.

Signature

RegexReplaceAllLiteral(regex string, s string, repl string) (string, error)
{{ regexReplaceAllLiteral "world", "hello world", "$1" }} // Output: "hello $1", nil
{{ regexReplaceAllLiteral "world", "hello world", "\invalid$^///" }} // Output: "", error

regexQuoteMeta

The function returns a version of the provided string that can be used as a literal pattern in a regular expression, escaping any special characters.

Signature

RegexQuoteMeta(str string) string
{{ regexQuoteMeta ".+*?^$()[]{}|" }} // Output: "\.\+\*\?\^\$\(\)\[\]\{\}\|"

Last updated

Change request #24: reflect safe functions feature and new signatures