regexpstruct

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2023 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Overview

Package regexpstruct extends regexp to store submatches into structs.

Regexp is a generic type that extends regexp.Regexp to provide additional methods that store capture results into a given struct, matching struct tags with captures names.

The following methods are exposed: * Regexp.FindStringStruct: similar to regexp.FindStringSubmatch * Regexp.FindAllStringStruct: similar to regexp.FindAllStringSubmatch

Example
package main

import (
	"fmt"

	"github.com/dolmen-go/regexpstruct"
)

func main() {
	type pair struct {
		K string `rx:"k"`
		V string `rx:"v"`
	}

	re := regexpstruct.MustCompile[pair](`^(?P<k>.*)=(?P<v>.*)\z`, "rx")

	fmt.Printf("%#v\n", re.SubexpNames())

	var p pair
	if re.FindStringStruct("a=b", &p) {
		fmt.Printf("%#v\n", p)
	}

}
Output:

[]string{"", "k", "v"}
regexpstruct_test.pair{K:"a", V:"b"}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Regexp

type Regexp[T any] struct {
	// contains filtered or unexported fields
}

func Compile

func Compile[T any](expr string, structTag string) (*Regexp[T], error)

Compile wraps regexp.Compile to extend regexp.Regexp.

Type T must be a struct type with struct tags structTag that should match names of submatches of the regexp. Submatches names are either integers or defined using the capturing group (?P<name>re) (see regexp/syntax) and are exposed by regexp.Regexp.SubexpNames. See also regexp.Regexp.Expand for capture naming constraints.

Recommended tag names: "re", "rx", or "regexp"

func MustCompile

func MustCompile[T any](expr string, structTag string) *Regexp[T]

MustCompile is like Compile but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.

func (*Regexp[T]) FindAllStringStruct

func (re *Regexp[T]) FindAllStringStruct(s string, n int) []T

FindAllStringStruct wraps regexp.Regexp.FinfAllStringSubmatch to store repeated captures a into a []T.

func (*Regexp[T]) FindStringStruct

func (re *Regexp[T]) FindStringStruct(s string, target *T) bool

FindStringStruct wraps regexp.Regexp.FindStringSubmatch to store submatches into a struct type value using struct tags.

Jump to

Keyboard shortcuts

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