RegEx

package
v0.0.0-...-535787f Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2025 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

A regular expression (or regex) is a compact language that can be used to recognize strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For example, a regex of ab[0-9] would find any string that is ab followed by any number from 0 to 9. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet.

To begin, the RegEx object needs to be compiled with the search pattern using Instance.Compile before it can be used.

package main

import "graphics.gd/classdb/RegEx"

func ExampleRegEx() {
	var regex = RegEx.New()
	regex.Compile(`\w-(\d+)`)
}

The search pattern must be escaped first for GDScript before it is escaped for the expression. For example, compile("\\d+") would be read by RegEx as \d+. Similarly, compile("\"(?:\\\\.|[^\"])*\"") would be read as "(?:\\.|[^"])*". In GDScript, you can also use raw string literals (r-strings). For example, compile(r'"(?:\\.|[^"])*"') would be read the same.

Using Instance.Search, you can find the pattern within the given text. If a pattern is found, graphics.gd/classdb/RegExMatch is returned and you can retrieve details of the results using methods such as graphics.gd/classdb/RegExMatch.Instance.GetString and graphics.gd/classdb/RegExMatch.Instance.GetStart.

package main

import (
	"graphics.gd/classdb/RegEx"
	"graphics.gd/classdb/RegExMatch"
)

func ExampleRegExSearch() {
	var regex = RegEx.New()
	regex.Compile(`\w-(\d+)`)
	result := regex.Search("abc n-0123")
	if result != RegExMatch.Nil {
		print(result.GetString()) // Would print n-0123
	}
}

The results of capturing groups () can be retrieved by passing the group number to the various methods in graphics.gd/classdb/RegExMatch. Group 0 is the default and will always refer to the entire pattern. In the above example, calling result.get_string(1) would give you 0123.

This version of RegEx also supports named capturing groups, and the names can be used to retrieve the results. If two or more groups have the same name, the name would only refer to the first one with a match.

package main

import (
	"fmt"

	"graphics.gd/classdb/RegEx"
	"graphics.gd/classdb/RegExMatch"
)

func ExampleRegExCapture() {
	var regex = RegEx.New()
	regex.Compile(`d(?<digit>[0-9]+)|x(?<digit>[0-9a-f]+)`)
	result := regex.Search("the number is x2f")
	if result != RegExMatch.Nil {
		fmt.Print(RegExMatch.Expanded(result).GetString("digit")) // Would print 2f
	}
}

If you need to process multiple results, Instance.SearchAll generates a list of all non-overlapping results. This can be combined with a for loop for convenience.

package main

import (
	"fmt"

	"graphics.gd/classdb/RegEx"
	"graphics.gd/classdb/RegExMatch"
)

func ExampleRegExSearchAll() {
	var regex = RegEx.New()
	regex.Compile(`d(?<digit>[0-9]+)|x(?<digit>[0-9a-f]+)`)
	for _, result := range regex.SearchAll("the numbers are d42 and x2f") {
		fmt.Println(RegExMatch.Expanded(result).GetString("digit"))
	}
}

Example: Split a string using a RegEx:

package main

import (
	"fmt"

	"graphics.gd/classdb/RegEx"
)

func ExampleRegExSplit() {
	var regex = RegEx.New()
	regex.Compile(`\S+`) // Negated whitespace character class.
	var results = []string{}
	for _, result := range regex.SearchAll("One  Two \n\tThree") {
		results = append(results, result.GetString())
	}
	fmt.Println(results)
}

Note: Godot's regex implementation is based on the PCRE2 library. You can view the full pattern reference here.

Tip: You can use Regexr to test regular expressions online.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Advanced

type Advanced = class

Advanced exposes a 1:1 low-level instance of the class, undocumented, for those who know what they are doing.

type Any

type Any interface {
	gd.IsClass
	AsRegEx() Instance
}

type Expanded

type Expanded [1]gdclass.RegEx

func (Expanded) Compile

func (self Expanded) Compile(pattern string, show_error bool) error

Compiles and assign the search pattern to use. Returns [Ok] if the compilation is successful. If compilation fails, returns [Failed] and when 'show_error' is true, details are printed to standard output.

func (Expanded) Search

func (self Expanded) Search(subject string, offset int, end int) RegExMatch.Instance

Searches the text for the compiled pattern. Returns a graphics.gd/classdb/RegExMatch container of the first matching result if found, otherwise null.

The region to search within can be specified with 'offset' and 'end'. This is useful when searching for another match in the same 'subject' by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor ^ is not affected by 'offset', and the character before 'offset' will be checked for the word boundary \b.

func (Expanded) SearchAll

func (self Expanded) SearchAll(subject string, offset int, end int) []RegExMatch.Instance

Searches the text for the compiled pattern. Returns an array of graphics.gd/classdb/RegExMatch containers for each non-overlapping result. If no results were found, an empty array is returned instead.

The region to search within can be specified with 'offset' and 'end'. This is useful when searching for another match in the same 'subject' by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor ^ is not affected by 'offset', and the character before 'offset' will be checked for the word boundary \b.

func (Expanded) Sub

func (self Expanded) Sub(subject string, replacement string, all bool, offset int, end int) string

Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as $1 and $name are expanded and resolved. By default, only the first instance is replaced, but it can be changed for all instances (global replacement).

The region to search within can be specified with 'offset' and 'end'. This is useful when searching for another match in the same 'subject' by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor ^ is not affected by 'offset', and the character before 'offset' will be checked for the word boundary \b.

type Extension

type Extension[T gdclass.Interface] struct{ gdclass.Extension[T, Instance] }

Extension can be embedded in a new struct to create an extension of this class. T should be the type that is embedding this Extension

func (*Extension[T]) AsObject

func (self *Extension[T]) AsObject() [1]gd.Object

func (*Extension[T]) AsRefCounted

func (self *Extension[T]) AsRefCounted() [1]gd.RefCounted

func (*Extension[T]) AsRegEx

func (self *Extension[T]) AsRegEx() Instance

type ID

type ID Object.ID

ID is a typed object ID (reference) to an instance of this class, use it to store references to objects with unknown lifetimes, as an ID will not panic on use if the underlying object has been destroyed.

func (ID) Instance

func (id ID) Instance() (Instance, bool)

type Instance

type Instance [1]gdclass.RegEx

Instance of the class with convieniently typed arguments and results.

var Nil Instance

Nil is a nil/null instance of the class. Equivalent to the zero value.

func CreateFromString

func CreateFromString(pattern string) Instance

Creates and compiles a new graphics.gd/classdb/RegEx object. See also Instance.Compile.

func CreateFromStringOptions

func CreateFromStringOptions(pattern string, show_error bool) Instance

Creates and compiles a new graphics.gd/classdb/RegEx object. See also Instance.Compile.

func New

func New() Instance

func (Instance) AsObject

func (self Instance) AsObject() [1]gd.Object

func (Instance) AsRefCounted

func (self Instance) AsRefCounted() [1]gd.RefCounted

func (Instance) AsRegEx

func (self Instance) AsRegEx() Instance

func (Instance) Clear

func (self Instance) Clear()

This method resets the state of the object, as if it was freshly created. Namely, it unassigns the regular expression of this object.

func (Instance) Compile

func (self Instance) Compile(pattern string) error

Compiles and assign the search pattern to use. Returns [Ok] if the compilation is successful. If compilation fails, returns [Failed] and when 'show_error' is true, details are printed to standard output.

func (Instance) GetGroupCount

func (self Instance) GetGroupCount() int

Returns the number of capturing groups in compiled pattern.

func (Instance) GetNames

func (self Instance) GetNames() []string

Returns an array of names of named capturing groups in the compiled pattern. They are ordered by appearance.

func (Instance) GetPattern

func (self Instance) GetPattern() string

Returns the original search pattern that was compiled.

func (Instance) ID

func (self Instance) ID() ID

func (Instance) IsValid

func (self Instance) IsValid() bool

Returns whether this object has a valid search pattern assigned.

func (Instance) Search

func (self Instance) Search(subject string) RegExMatch.Instance

Searches the text for the compiled pattern. Returns a graphics.gd/classdb/RegExMatch container of the first matching result if found, otherwise null.

The region to search within can be specified with 'offset' and 'end'. This is useful when searching for another match in the same 'subject' by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor ^ is not affected by 'offset', and the character before 'offset' will be checked for the word boundary \b.

func (Instance) SearchAll

func (self Instance) SearchAll(subject string) []RegExMatch.Instance

Searches the text for the compiled pattern. Returns an array of graphics.gd/classdb/RegExMatch containers for each non-overlapping result. If no results were found, an empty array is returned instead.

The region to search within can be specified with 'offset' and 'end'. This is useful when searching for another match in the same 'subject' by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor ^ is not affected by 'offset', and the character before 'offset' will be checked for the word boundary \b.

func (*Instance) SetObject

func (self *Instance) SetObject(obj [1]gd.Object) bool

func (Instance) Sub

func (self Instance) Sub(subject string, replacement string) string

Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as $1 and $name are expanded and resolved. By default, only the first instance is replaced, but it can be changed for all instances (global replacement).

The region to search within can be specified with 'offset' and 'end'. This is useful when searching for another match in the same 'subject' by calling this method again after a previous success. Note that setting these parameters differs from passing over a shortened string. For example, the start anchor ^ is not affected by 'offset', and the character before 'offset' will be checked for the word boundary \b.

func (Instance) Virtual

func (self Instance) Virtual(name string) reflect.Value

Jump to

Keyboard shortcuts

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