pcregexp

package module
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 16, 2025 License: Apache-2.0 Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

pcregexp

Tests Go Reference

pcregexp is a drop‑in replacement for Go's standard regexp package that uses the full capabilities of PCRE2 by loading the shared library dynamically at runtime, which enables cross‑compilation without the need for a C compiler (no Cgo required!). The API closely mirrors that of the standard library's regexp package while supporting advanced regex features like lookarounds and backreferences that PCRE2 provides.

[!WARNING] PCRE2 supports features that can lead to exponential runtime in some cases. Use pcregexp only with trusted regex patterns to avoid potential regular expression denial-of-service (ReDoS) issues (CWE-1333) or configure a global match context to impose limits and control resource usage by using SetMatchContext function.

Requirements

  • go1.20 or later.
  • PCRE2 10.x shared library must be installed on your system.
  • Supported platforms:

Install

go install -v github.com/dwisiswant0/pcregexp@latest

Usage

package main

import (
    "fmt"
    
    "github.com/dwisiswant0/pcregexp"
)

func main() {
    // Compile a pattern. (Panics on error)
    re := pcregexp.MustCompile("p([a-z]+)ch")
    defer re.Close()

    // Check if the string matches the pattern.
    fmt.Println("MatchString(\"peach\"):", re.MatchString("peach"))

    // Find the leftmost match.
    fmt.Println("FindString(\"peach punch\"):", re.FindString("peach punch"))

    // Get the start and end indexes of the match.
    fmt.Println("FindStringIndex(\"peach punch\"):", re.FindStringIndex("peach punch"))

    // Retrieve the match along with its captured submatch.
    fmt.Println("FindStringSubmatch(\"peach punch\"):", re.FindStringSubmatch("peach punch"))

    // Perform global replacement (naively replaces all non-overlapping matches).
    src := "peach punch pinch"
    repl := "<fruit>"
    fmt.Println("ReplaceAllString:", re.ReplaceAllString(src, repl))
}

Wrapped Regexp API

Go Reference

You may want to use the regexp package provided here, which wraps both Go's standard regexp package and a PCRE2-based implementation, pcregexp. This unified interface automatically selects the appropriate engine based on the regex features used, offering the best of both worlds.

Benchmark

Execute the performance benchmark by running:

make bench

TODO

See TODO.md.

Status

[!CAUTION] pcregexp has NOT reached 1.0 yet. Therefore, this library is currently not supported and does not offer a stable API; use at your own risk.

There are no guarantees of stability for the APIs in this library, and while they are not expected to change dramatically. API tweaks and bug fixes may occur.

License

pcregexp is released by @dwisiswant0 under the Apache 2.0 license. See LICENSE.

Documentation

Index

Constants

View Source
const (
	// DefaultJITStackStartSize is the default initial size of the JIT stack.
	DefaultJITStackStartSize = uint64(32 * 1024) // 32 KiB initial size

	// DefaultJITStackMaxSize is the default maximum size of the JIT stack.
	DefaultJITStackMaxSize = uint64(512 * 1024) // 512 KiB max size
)

Default stack sizes for JIT compilation These values are used to set the initial and maximum stack sizes for the JIT compiler when compiling regular expressions. The default values are set to reasonable sizes for most use cases. The initial size is the amount of stack space allocated when the JIT compiler is first created, and the maximum size is the maximum amount of stack space that can be allocated during JIT compilation. These values can be adjusted based on the specific needs of the application and the complexity of the regular expressions being compiled by using the SetJITStackSize function.

Variables

This section is empty.

Functions

func Match added in v0.2.0

func Match(pattern string, b []byte) (matched bool, err error)

Match reports whether the byte slice b contains any match of the regular expression pattern. More complicated queries need to use Compile and the full [Regexp] interface.

Note: an empty pattern is considered valid but will match nothing. :shrug:

func MatchReader added in v0.2.0

func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)

MatchReader reports whether the text returned by the io.RuneReader contains any match of the regular expression pattern. More complicated queries need to use Compile and the full [Regexp] interface.

Note: an empty pattern is considered valid but will match nothing. :shrug:

func MatchString added in v0.2.0

func MatchString(pattern string, s string) (matched bool, err error)

MatchString reports whether the string s contains any match of the regular expression pattern. More complicated queries need to use Compile and the full [Regexp] interface.

Note: an empty pattern is considered valid but will match nothing. :shrug:

func NeedsPCRE added in v0.3.0

func NeedsPCRE(pattern string) bool

NeedsPCRE checks if the pattern contains PCRE2-only features, based on pcre2syntax.

Ref: https://pcre2project.github.io/pcre2/doc/pcre2syntax/

func SetJITOption added in v0.3.0

func SetJITOption(option JITOption)

SetJITOption sets the default JIT option used for JIT compilation. The option parameter specifies the JIT option to be used. The default option is JITComplete, which enables full JIT compilation.

func SetJITStackSize added in v0.3.0

func SetJITStackSize(startSize, maxSize uint64)

SetJITStackSize sets the default JIT stack sizes used for JIT compilation. The startSize parameter sets the initial stack size, and maxSize sets the maximum size it can grow to.

The default number is 32 KiB for startSize and 512 KiB for maxSize.

func SetMatchContext added in v0.2.0

func SetMatchContext(ctx MatchContext) error

SetMatchContext sets the global match context used by all regex operations.

This is useful to globally limit regex matching complexity to prevent ReDoS attacks. If the context is not set, no limits are enforced.

Types

type JITOption added in v0.3.1

type JITOption uint32

JITOption represents the JIT compilation options. It is used to specify the level of JIT compilation to be performed.

The default option is JITComplete, which enables full JIT compilation. The JIT compilation options are used to control the behavior of the JIT compiler when compiling regular expressions. The options can be set using the SetJITOption function.

const (
	JITNoJit JITOption = iota
	JITComplete
	JITPartialSoft

	JITPartialHard // 4
)

type MatchContext added in v0.2.0

type MatchContext struct {

	// MatchLimit is the maximum number of matches to allow.
	MatchLimit uint32

	// DepthLimit is the maximum recursion depth to allow.
	DepthLimit uint32
	// contains filtered or unexported fields
}

MatchContext provides configuration for regex matching operations.

type PCREgexp added in v0.0.2

type PCREgexp struct {
	// contains filtered or unexported fields
}

PCREgexp is a compiled regular expression.

func Compile

func Compile(pattern string) (*PCREgexp, error)

Compile creates a new PCREgexp from pattern.

Note: an empty pattern is considered valid but will match nothing. :shrug: In this case, calling [Close] is unnecessary.

func MustCompile

func MustCompile(pattern string) *PCREgexp

MustCompile is like Compile but panics on error.

Note: an empty pattern is considered valid but will match nothing. :shrug: In this case, calling [Close] is unnecessary.

func (*PCREgexp) Close added in v0.0.2

func (re *PCREgexp) Close()

Close frees the resources associated with the compiled pattern.

func (*PCREgexp) Expand added in v0.0.3

func (re *PCREgexp) Expand(dst, template, src []byte, match []int) []byte

Expand appends template to dst and returns the result; during the append, Expand replaces variables in the template with corresponding matches drawn from src.

func (*PCREgexp) ExpandString added in v0.0.3

func (re *PCREgexp) ExpandString(dst []byte, template, src string, match []int) []byte

ExpandString is like Expand but the template and source are strings.

func (*PCREgexp) Find added in v0.0.2

func (re *PCREgexp) Find(b []byte) []byte

Find returns a slice holding the text of the leftmost match in b.

func (*PCREgexp) FindAll added in v0.0.3

func (re *PCREgexp) FindAll(b []byte, n int) [][]byte

FindAll returns a slice of all successive matches of the regexp in b.

func (*PCREgexp) FindAllIndex added in v0.0.3

func (re *PCREgexp) FindAllIndex(b []byte, n int) [][]int

FindAllIndex returns a slice of index pairs identifying successive matches of the regexp in b.

func (*PCREgexp) FindAllString added in v0.0.2

func (re *PCREgexp) FindAllString(s string, n int) []string

FindAllString returns a slice of all successive matches of the regexp in s. If n < 0, the return value contains all matches. If n >= 0, the return value contains at most n matches.

func (*PCREgexp) FindAllStringIndex added in v0.0.2

func (re *PCREgexp) FindAllStringIndex(s string, n int) [][]int

FindAllStringIndex returns a slice of index pairs identifying successive matches of the regexp in s.

func (*PCREgexp) FindAllStringSubmatch added in v0.0.2

func (re *PCREgexp) FindAllStringSubmatch(s string, n int) [][]string

FindAllStringSubmatch is like [FindStringSubmatch] but returns successive matches.

func (*PCREgexp) FindAllStringSubmatchIndex added in v0.0.3

func (re *PCREgexp) FindAllStringSubmatchIndex(s string, n int) [][]int

FindAllStringSubmatchIndex returns a slice of slices holding the index pairs identifying the successive matches of the regexp in s and their subexpressions.

func (*PCREgexp) FindAllSubmatch added in v0.0.3

func (re *PCREgexp) FindAllSubmatch(b []byte, n int) [][][]byte

FindAllSubmatch returns a slice of successive matches of the regexp in b.

func (*PCREgexp) FindAllSubmatchIndex added in v0.0.3

func (re *PCREgexp) FindAllSubmatchIndex(b []byte, n int) [][]int

FindAllSubmatchIndex returns a slice of successive matches indexes of the regexp in b.

func (*PCREgexp) FindIndex added in v0.0.2

func (re *PCREgexp) FindIndex(b []byte) []int

FindIndex returns a two-element slice of integers defining the location of the leftmost match in b.

func (*PCREgexp) FindReaderIndex added in v0.0.3

func (re *PCREgexp) FindReaderIndex(r io.RuneReader) []int

FindReaderIndex returns a two-element slice of integers defining the location of the leftmost match in text read from the RuneReader. A return value of nil indicates no match.

func (*PCREgexp) FindReaderSubmatchIndex added in v0.0.3

func (re *PCREgexp) FindReaderSubmatchIndex(r io.RuneReader) []int

FindReaderSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regexp in text read from the RuneReader, and the matches of its subexpressions. A return value of nil indicates no match.

func (*PCREgexp) FindString added in v0.0.2

func (re *PCREgexp) FindString(s string) string

FindString returns the text of the leftmost match in s.

func (*PCREgexp) FindStringIndex added in v0.0.2

func (re *PCREgexp) FindStringIndex(s string) []int

FindStringIndex returns a two-element slice of integers defining the start and end of the leftmost match in s.

func (*PCREgexp) FindStringSubmatch added in v0.0.2

func (re *PCREgexp) FindStringSubmatch(s string) []string

FindStringSubmatch returns a slice holding the text of the leftmost match and its submatches. It uses the actual number of captured groups as returned by PCRE2.

func (*PCREgexp) FindStringSubmatchIndex added in v0.0.3

func (re *PCREgexp) FindStringSubmatchIndex(s string) []int

FindStringSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regexp in s and the matches of its subexpressions.

func (*PCREgexp) FindSubmatch added in v0.0.2

func (re *PCREgexp) FindSubmatch(b []byte) [][]byte

FindSubmatch returns a slice of slices holding the text of the leftmost match and the matches of any subexpressions.

func (*PCREgexp) FindSubmatchIndex added in v0.0.2

func (re *PCREgexp) FindSubmatchIndex(b []byte) []int

FindSubmatchIndex returns a slice holding the index pairs identifying the leftmost match and the matches of any subexpressions.

func (*PCREgexp) LiteralPrefix added in v0.0.3

func (re *PCREgexp) LiteralPrefix() (prefix string, complete bool)

LiteralPrefix returns a literal string that must begin any match of the regular expression. It also returns a boolean indicating whether the literal is the entire regular expression.

TODO(dwisiswant0): Implement this method.

func (*PCREgexp) Longest added in v0.0.3

func (re *PCREgexp) Longest()

Longest makes future searches prefer the longest match. For PCRE2, this would require changing match flags, but since we're using a basic match function, this is currently a no-op.

TODO(dwisiswant0): Implement this method.

func (*PCREgexp) MarshalText added in v0.0.3

func (re *PCREgexp) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*PCREgexp) Match added in v0.0.2

func (re *PCREgexp) Match(b []byte) bool

Match reports whether the regexp matches the byte slice b.

func (*PCREgexp) MatchReader added in v0.0.3

func (re *PCREgexp) MatchReader(r io.RuneReader) bool

MatchReader reports whether the regexp matches the text read from the RuneReader.

func (*PCREgexp) MatchString added in v0.0.2

func (re *PCREgexp) MatchString(s string) bool

MatchString reports whether the Regexp matches the given string.

func (*PCREgexp) NumSubexp added in v0.0.2

func (re *PCREgexp) NumSubexp() int

NumSubexp returns the number of parenthesized subexpressions in this regexp.

TODO(dwisiswant0): Implement this method.

func (*PCREgexp) ReplaceAll added in v0.0.2

func (re *PCREgexp) ReplaceAll(src, repl []byte) []byte

ReplaceAll returns a copy of src, replacing matches of the regexp with repl.

func (*PCREgexp) ReplaceAllFunc added in v0.0.2

func (re *PCREgexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte

ReplaceAllFunc returns a copy of src in which all matches of the regexp have been replaced by the return value of function repl applied to the matched byte slice.

func (*PCREgexp) ReplaceAllLiteral added in v0.0.3

func (re *PCREgexp) ReplaceAllLiteral(src, repl []byte) []byte

ReplaceAllLiteral returns a copy of src, replacing matches of the regexp with repl.

func (*PCREgexp) ReplaceAllLiteralString added in v0.0.3

func (re *PCREgexp) ReplaceAllLiteralString(src, repl string) string

ReplaceAllLiteralString returns a copy of src, replacing matches of the regexp with repl.

func (*PCREgexp) ReplaceAllString added in v0.0.2

func (re *PCREgexp) ReplaceAllString(src, repl string) string

ReplaceAllString returns a copy of src in which all matches of the PCREgexp have been replaced by repl.

If an empty match is encountered, it advances one UTF-8 rune to avoid infinite loop.

func (*PCREgexp) ReplaceAllStringFunc added in v0.0.3

func (re *PCREgexp) ReplaceAllStringFunc(src string, repl func(string) string) string

ReplaceAllStringFunc returns a copy of src in which all matches of the regexp have been replaced by the return value of function repl applied to the matched text.

func (*PCREgexp) Split added in v0.0.2

func (re *PCREgexp) Split(s string, n int) []string

Split slices s into substrings separated by matches of the regexp. If n > 0, Split returns at most n substrings, otherwise it returns all substrings.

func (*PCREgexp) String added in v0.0.2

func (re *PCREgexp) String() string

String returns the source text used to compile the regexp.

func (*PCREgexp) SubexpIndex added in v0.0.3

func (re *PCREgexp) SubexpIndex(name string) int

SubexpIndex returns the index of the first subexpression with the given name, or -1 if there is no subexpression with that name.

TODO(dwisiswant0): Implement this method.

func (*PCREgexp) SubexpNames added in v0.0.3

func (re *PCREgexp) SubexpNames() []string

SubexpNames returns the names of the parenthesized subexpressions in this regexp. The name for the first sub-expression is at index 1, following the same convention as index in FindSubmatch.

TODO(dwisiswant0): Implement this method.

func (*PCREgexp) UnmarshalText added in v0.0.3

func (re *PCREgexp) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

Directories

Path Synopsis
pkg
regexp
Package regexp provides a drop-in replacement for Go's standard regexp package with added support for Perl-compatible regular expressions (PCRE).
Package regexp provides a drop-in replacement for Go's standard regexp package with added support for Perl-compatible regular expressions (PCRE).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址