Browse by type
Regexp2 is a feature-rich RegExp engine for Go. It doesn't have constant time guarantees like the built-in regexp package, but it allows backtracking and is compatible with Perl5 and .NET. You'll likely be better off with the RE2 engine from the regexp package and should only use this if you need to write very complex patterns or require compatibility with .NET.
The engine is ported from the .NET framework's System.Text.RegularExpressions.Regex engine. That engine was open sourced in 2015 under the MIT license. There are some fundamental differences between .NET strings and Go strings that required a bit of borrowing from the Go framework regex engine as well. The engine retains .NET-style syntax and matching features, with the compatibility priorities described below.
For extra performance use regexp2 with regexp2cg. It is a code generation utility for regexp2 and you can likely improve your regexp runtime performance by 3-10x in hot code paths. As always you should benchmark your specifics to confirm the results. Give it a try!
This is a go-gettable library, so install is easy:
go get github.com/dlclark/regexp2/v2@latest
Version 2 includes changes that may affect compatibility with existing v1 users:
github.com/dlclark/regexp2/v2, so imports need to use the /v2 suffix.Regexp.Split is now available for splitting strings with regexp matches.compat sub-package provides a regexp compatibility adapter with the same Find* and Match* method signatures as regexp.Regexp, plus a compat.Matcher interface that is implemented by both *regexp.Regexp and the adapter.Compile and MustCompile now use variadic compile options for regex behavior and memory/performance tuning. See Compile options for more details.regexp2.Debug and regexp2.Compile to new regexp2.OptionDebug() and regexp2.OptionIsCodeGen() compile options.syntax package have been exported or changed to support code generation.regexp2.ECMAScript option to be closer to the ECMAScript standard rather than C#'s ECMAScript behavior.Capture.Index and Capture.Length to Capture.RuneIndex and Capture.RuneLength to be more clear that we're dealing with rune offsets.Capture.ByteRange() to return the byte offset index and length of the captured text. This requires some additional processing to be done behind the scenes the first time it's called for a given capture to convert the native rune offsets to byte offsets.Usage is similar to the Go regexp package. Just like in regexp, you start by converting a regex into a state machine via the Compile or MustCompile methods. They ultimately do the same thing, but MustCompile will panic if the regex is invalid. You can then use the provided Regexp struct to find matches repeatedly. A Regexp struct is safe to use across goroutines.
re := regexp2.MustCompile(`Your pattern`)
if isMatch, _ := re.MatchString(`Something to match`); isMatch {
//do something
}
The *Match* methods can return an error wrapping ErrMatchTimeout if you set the re.MatchTimeout field, or ErrBacktrackingStackLimit if a match exceeds its configured backtracking stack size. Any other error is a bug in the regexp2 package. If you need more details about capture groups in a match then use the FindStringMatch method, like so:
if m, _ := re.FindStringMatch(`Something to match`); m != nil {
// the whole match is always group 0
fmt.Printf("Group 0: %v\n", m.String())
// you can get all the groups too
gps := m.Groups()
// a group can be captured multiple times, so each cap is separately addressable
fmt.Printf("Group 1, first capture", gps[1].Captures[0].String())
fmt.Printf("Group 1, second capture", gps[1].Captures[1].String())
}
Group 0 is embedded in the Match. Group 0 is an automatically-assigned group that encompasses the whole pattern. This means that m.String() is the same as m.Group.String() and m.Groups()[0].String()
The last capture is embedded in each group, so g.String() will return the same thing as g.Capture.String() and g.Captures[len(g.Captures)-1].String().
In ECMAScript mode, duplicate group names are allowed in separate alternatives and keep distinct group numbers. GroupByName(name) selects the participating group (or the first if none participated); GroupNumberFromName(name) always returns the first declaration's number, which may differ from the selected group.
In ECMAScript mode, captures inside a quantified group are cleared before each repetition. Only the final successful repetition's captures remain; a group that does not participate in that repetition has no captures, and its backreference matches the empty string. Other modes retain capture history across repetitions.
If you want to find multiple matches from a single input string you should use the FindNextMatch method. For example, to implement a function similar to regexp.FindAllString:
func regexp2FindAllString(re *regexp2.Regexp, s string) []string {
var matches []string
m, _ := re.FindStringMatch(s)
for m != nil {
matches = append(matches, m.String())
m, _ = re.FindNextMatch(m)
}
return matches
}
FindNextMatch is optmized so that it re-uses the underlying string/rune slice.
For capture positions on rune input, FindRunesMatches avoids allocating a full
Match and its text metadata for every result:
input := []rune("first=one second=two")
re := regexp2.MustCompile(`(\w+)=(\w+)`)
err := re.FindRunesMatches(input, -1, func(view regexp2.MatchView) bool {
index, length, ok := view.GroupRange(2)
if ok {
fmt.Println(string(input[index : index+length]))
}
return true // return false to stop successfully
})
if err != nil {
// Handle a timeout or backtracking-stack limit error.
log.Fatal(err)
}
MatchView exposes only GroupRange and GroupCount. Group 0 is the whole match;
other groups report their last remaining capture. A participating empty capture
has ok == true and length 0, while an unmatched or fully balanced group has
ok == false. Ranges use rune indexes in the original input, even with a nonzero
startAt. For explicitly numbered groups, use re.GetGroupNumbers() to enumerate
their possibly sparse numbers. ECMAScript capture clearing and duplicate-name
group numbering follow the same rules as the full matching API.
The view borrows reusable engine storage and is valid only during its callback. Save returned indexes and lengths to keep results; copying the view does not extend its lifetime. Do not modify the input during iteration. Initial setup and buffer growth may allocate, but range lookup does not. Use the full matching API when you need capture histories or independently owned matches.
The internals of regexp2 always operate on []rune so RuneIndex and RuneLength data in a Match always reference a position in runes rather than bytes (even if the input was given as a string). ByteRange() provides UTF-8 byte offsets, matching the original string input for string APIs. It's advisable to use the provided String() methods when you do not need explicit offsets. ByteRange() lazily caches byte offsets on the shared match text, so the first call on captures from the same match is not safe to run concurrently with other ByteRange() calls on that match.
regexp2's behavior and compatibility goals are different depending on the mode.
| Mode | Compatibility priority |
|---|---|
| Default | .NET-style syntax and matching features, with Go's Unicode simple case folding preferred over exact .NET casing behavior. |
RE2 |
Go's regexp semantics where features overlap, while retaining regexp2 extensions. |
ECMAScript |
The ECMAScript specification, including the distinction between legacy case-insensitive matching (/i) and Unicode case-insensitive matching (/iu). |
Outside ECMAScript mode, IgnoreCase targets the locale-independent simple folding used by Go's regexp and unicode.SimpleFold. For example, (?i)^[a-z]$ matches the Kelvin sign K and long s ſ, and (?i)^Σ$ matches final sigma ς. Differences from .NET's culture-sensitive or culture-invariant casing are intentional when they follow Go's simple folding. The engine does not select casing rules from the process locale. Simple folding does not perform Unicode normalization or multi-character expansion: (?i)^ss$ does not match ß. Go's folding tables follow the Unicode version supplied by the consumer's Go toolchain.
Case folding and character-class definitions are separate choices. Default mode retains .NET-style Unicode word classes, so \w matches é; RE2 mode uses Go's ASCII word-class definition. Adopting Go's folding rules does not replace all default character classes with Go's definitions.
With ECMAScript|IgnoreCase, legacy folding prevents non-ASCII characters from folding into ASCII: ^[a-z]$ matches K but not K or ſ. Adding Unicode selects ECMAScript /iu behavior, which allows those matches and includes K and ſ in \w. \W is the complement of that mode's word class. The Unicode option selects ECMAScript Unicode behavior when combined with ECMAScript; it is not a switch for enabling Unicode folding in default mode.
Case-insensitive backreferences use the same folding policy: in default mode, both (?i)^ss$ and (?i)^(s)\1$ match sſ. The flags at the backreference determine whether its comparison ignores case, independently of the flags used to capture the text. These priorities are compatibility targets, not a guarantee of complete conformance; inconsistencies within a mode are bugs under this policy.
regexp2 supports Unicode character classes with \p{...} and negated classes with \P{...}. Outside ECMAScript Unicode mode, it also accepts the RE2/PCRE-style one-letter form, such as \pL.
Outside ECMAScript|Unicode mode, the class name may be a Go Unicode category, category alias, script, or property exposed by the Go standard library Unicode tables. For example:
letter := regexp2.MustCompile(`\p{L}+`)
katakana := regexp2.MustCompile(`\p{Katakana}+`)
notEmoji := regexp2.MustCompile(`\P{Emoji}+`)
Outside ECMAScript|Unicode mode, regexp2 also supports Unicode property selection syntax in the form \p{property=value}. Property and value aliases are matched loosely: case, hyphens, and underscores are ignored. For example, \p{GCB=RI}, \p{grapheme_cluster_break=regional_indicator}, and \p{grapheme-cluster-break=regional-indicator} all refer to the same class.
Valid property names and aliases come from Unicode 17.0.0 PropertyAliases.txt. Valid property values and aliases come from Unicode 17.0.0 PropertyValueAliases.txt. The generated tables use Unicode 17.0.0 data from DerivedCoreProperties.txt, emoji/emoji-data.txt, auxiliary/GraphemeBreakProperty.txt, auxiliary/WordBreakProperty.txt, and auxiliary/SentenceBreakProperty.txt for the package-local properties whose data changes more frequently than the Go standard library tables.
The default mode supports the following syntax:
\Q...\E quotes every character between \Q and \E. If \E is omitted, quoting continues to the end of the pattern. This also works inside character classes.\R matches one Unicode newline sequence: CRLF as a single sequence, or LF, VT, FF, CR, NEL, line separator, or paragraph separator.\X atomically matches one Unicode 17.0.0 extended grapheme cluster. This includes combining sequences, Hangul syllables, regional-indicator pairs, emoji ZWJ sequences, and Indic conjuncts.+ after a quantifier makes it possessive: *+, ++, ?+, and {m,n}+. For example, a*+ is equivalent to (?>a*) and will not give characters back when the remainder of the pattern fails.RE2 mode also supports \Q...\E and possessive quantifiers, but keeps \R and \X as literal R and X identity escapes. ECMAScript mode does not enable any of this syntax: \Q, \E, \R, and \X retain ECMAScript identity-escape behavior, and possessive quantifiers remain invalid.
regexp compatibility adapterThe github.com/dlclark/regexp2/v2/compat package provides an adapter for callers that want the same Find* and Match* method signatures as the standard library's regexp.Regexp, while still using the regexp2 engine.
```go import ( "github.com/dlclark/regexp2/v2" "github.com/dlclark/regexp2/v2/compat" )
re := compat.MustCompile(Your pattern, regexp2.RE2)
if re.MatchString(Something to match) {
// do something
}
matches := re.FindAllString(abc axbc, -1)
_ = mat
browse all types & interfaces →
$ claude mcp add regexp2 \
-- python -m otcore.mcp_server <graph>