Index · Object → RefCounted → RegEx

RegEx

Class for searching text for patterns using regular expressions.

Class Description

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 compile() before it can be used. Alternatively, the static method create_from_string() can be used to create and compile a RegEx object in a single method call.

var regex = RegEx.new()
regex.compile("\\w-(\\d+)")
# Shorthand to create and compile a regex (used in the examples below):
var regex2 = RegEx.create_from_string("\\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 search(), you can find the pattern within the given text. If a pattern is found, RegExMatch is returned and you can retrieve details of the results using methods such as RegExMatch.get_string() and RegExMatch.get_start().

var regex = RegEx.create_from_string("\\w-(\\d+)")
var result = regex.search("abc n-0123")
if result:
	print(result.get_string()) # Prints "n-0123"

The results of capturing groups () can be retrieved by passing the group number to the various methods in 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.

var regex = RegEx.create_from_string("d(?<digit>[0-9]+)|x(?<digit>[0-9a-f]+)")
var result = regex.search("the number is x2f")
if result:
	print(result.get_string("digit")) # Prints "2f"

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

# Prints "01 03 0 3f 42"
for result in regex.search_all("d01, d03, d0c, x3f and x42"):
	print(result.get_string("digit"))

Example: Split a string using a RegEx:

var regex = RegEx.create_from_string("\\S+") # Negated whitespace character class.
var results = []
for result in regex.search_all("One  Two \n\tThree"):
	results.push_back(result.get_string())
print(results) # Prints ["One", "Two", "Three"]

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.

Methods

func clear() -> void

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

func compile(pattern: String, show_error: bool = true) -> 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 create_from_string(pattern: String, show_error: bool = true) -> RegEx

Creates and compiles a new RegEx object. See also compile().

func get_group_count() -> int

Returns the number of capturing groups in compiled pattern.

func get_names() -> PackedStringArray

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

func get_pattern() -> String

Returns the original search pattern that was compiled.

func is_valid() -> bool

Returns whether this object has a valid search pattern assigned.

func search_all(subject: String, offset: int = 0, end: int = -1) -> RegExMatch[]

Searches the text for the compiled pattern. Returns an array of 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 sub(subject: String, replacement: String, all: bool = false, offset: int = 0, end: int = -1) -> 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.

Inherited from RefCounted (4)
func init_ref() -> bool
func reference() -> bool
func unreference() -> bool
Inherited from Object (62)
func _get(property: StringName) -> Variant
func _get_property_list() -> Dictionary[]
func _init() -> void
func _iter_get(iter: Variant) -> Variant
func _iter_init(iter: Array) -> bool
func _iter_next(iter: Array) -> bool
func _notification(what: int) -> void
func _set(property: StringName, value: Variant) -> bool
func _to_string() -> String
func _validate_property(property: Dictionary) -> void
func add_user_signal(signal: String, arguments: Array = []) -> void
func call(method: StringName) -> Variant
func callv(method: StringName, arg_array: Array) -> Variant
func cancel_free() -> void
func connect(signal: StringName, callable: Callable, flags: int = 0) -> Error
func disconnect(signal: StringName, callable: Callable) -> void
func emit_signal(signal: StringName) -> Error
func free() -> void
func get(property: StringName) -> Variant
func get_class() -> String
func get_incoming_connections() -> Dictionary[]
func get_indexed(property_path: NodePath) -> Variant
func get_meta(name: StringName, default: Variant = null) -> Variant
func get_meta_list() -> StringName[]
func get_method_list() -> Dictionary[]
func get_property_list() -> Dictionary[]
func get_signal_connection_list(signal: StringName) -> Dictionary[]
func get_signal_list() -> Dictionary[]
func has_meta(name: StringName) -> bool
func has_method(method: StringName) -> bool
func has_signal(signal: StringName) -> bool
func is_class(class: StringName) -> bool
func is_connected(signal: StringName, callable: Callable) -> bool
func notification(what: int, reversed: bool = false) -> void
func remove_meta(name: StringName) -> void
func remove_user_signal(signal: StringName) -> void
func set(property: StringName, value: Variant) -> void
func set_block_signals(enable: bool) -> void
func set_deferred(property: StringName, value: Variant) -> void
func set_indexed(property_path: NodePath, value: Variant) -> void
func set_message_translation(enable: bool) -> void
func set_meta(name: StringName, value: Variant) -> void
func set_script(script: Variant) -> void
func set_translation_domain(domain: StringName) -> void
func to_string() -> String
func tr(message: StringName, context: StringName = &"") -> String
func tr_n(message: StringName, plural_message: StringName, n: int, context: StringName = &"") -> String

Signals

Inherited from Object (2)