Class RegEx
- Namespace
- Godot
- Assembly
- GodotSharp.dll
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(string) before it can be used.
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 Search(string, int, int), 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 GetString(Variant?) and GetStart(Variant?).
var regex = RegEx.new()
regex.compile("\\w-(\\d+)")
var result = regex.search("abc n-0123")
if result:
print(result.get_string()) # Would print 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.new()
regex.compile("d(?<digit>[0-9]+)|x(?<digit>[0-9a-f]+)")
var result = regex.search("the number is x2f")
if result:
print(result.get_string("digit")) # Would print 2f
If you need to process multiple results, SearchAll(string, int, int) generates a list of all non-overlapping results. This can be combined with a for
loop for convenience.
for result in regex.search_all("d01, d03, d0c, x3f and x42"):
print(result.get_string("digit"))
# Would print 01 03 0 3f 42
Example of splitting a string using a RegEx:
var regex = RegEx.new()
regex.compile("\\S+") # Negated whitespace character class.
var results = []
for result in regex.search_all("One Two \n\tThree"):
results.push_back(result.get_string())
# The `results` array now contains "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.
public class RegEx : RefCounted, IDisposable
- Inheritance
-
RegEx
- Implements
- Inherited Members
Constructors
RegEx()
public RegEx()
Methods
Clear()
This method resets the state of the object, as if it was freshly created. Namely, it unassigns the regular expression of this object.
public void Clear()
Compile(string)
Compiles and assign the search pattern to use. Returns Ok if the compilation is successful. If an error is encountered, details are printed to standard output and an error is returned.
public Error Compile(string pattern)
Parameters
pattern
string
Returns
CreateFromString(string)
Creates and compiles a new RegEx object.
public static RegEx CreateFromString(string pattern)
Parameters
pattern
string
Returns
GetGroupCount()
Returns the number of capturing groups in compiled pattern.
public int GetGroupCount()
Returns
GetNames()
Returns an array of names of named capturing groups in the compiled pattern. They are ordered by appearance.
public string[] GetNames()
Returns
- string[]
GetPattern()
Returns the original search pattern that was compiled.
public string GetPattern()
Returns
HasGodotClassMethod(in godot_string_name)
Check if the type contains a method with the given name. This method is used by Godot to check if a method exists before invoking it. Do not call or override this method.
protected override bool HasGodotClassMethod(in godot_string_name method)
Parameters
method
godot_string_nameName of the method to check for.
Returns
HasGodotClassSignal(in godot_string_name)
Check if the type contains a signal with the given name. This method is used by Godot to check if a signal exists before raising it. Do not call or override this method.
protected override bool HasGodotClassSignal(in godot_string_name signal)
Parameters
signal
godot_string_nameName of the signal to check for.
Returns
InvokeGodotClassMethod(in godot_string_name, NativeVariantPtrArgs, out godot_variant)
Invokes the method with the given name, using the given arguments. This method is used by Godot to invoke methods from the engine side. Do not call or override this method.
protected override bool InvokeGodotClassMethod(in godot_string_name method, NativeVariantPtrArgs args, out godot_variant ret)
Parameters
method
godot_string_nameName of the method to invoke.
args
NativeVariantPtrArgsArguments to use with the invoked method.
ret
godot_variantValue returned by the invoked method.
Returns
IsValid()
Returns whether this object has a valid search pattern assigned.
public bool IsValid()
Returns
Search(string, int, int)
Searches the text for the compiled pattern. Returns a 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
.
public RegExMatch Search(string subject, int offset = 0, int end = -1)
Parameters
Returns
SearchAll(string, int, int)
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
.
public Array<RegExMatch> SearchAll(string subject, int offset = 0, int end = -1)
Parameters
Returns
Sub(string, string, bool, int, int)
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
.
public string Sub(string subject, string replacement, bool all = false, int offset = 0, int end = -1)