Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
RegEx
Eredita: RefCounted < Object
Classe per la ricerca di modelli nel testo, tramite espressioni regolari.
Descrizione
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.
Metodi
void |
clear() |
create_from_string(pattern: String, show_error: bool = true) static |
|
get_group_count() const |
|
get_names() const |
|
get_pattern() const |
|
is_valid() const |
|
search(subject: String, offset: int = 0, end: int = -1) const |
|
search_all(subject: String, offset: int = 0, end: int = -1) const |
|
sub(subject: String, replacement: String, all: bool = false, offset: int = 0, end: int = -1) const |
Descrizioni dei metodi
void clear() 🔗
Questo metodo reimposta lo stato dell'oggetto, come se fosse stato appena creato. Ovvero, annulla l'assegnazione dell'espressione regolare di questo oggetto.
Error compile(pattern: String, show_error: bool = true) 🔗
Compila e assegna il modello di ricerca da usare. Restituisce @GlobalScope.OK se la compilazione avviene con successo. Se si verifica un errore, restituisce @GlobalScope.FAILED e, se show_error è true, i dettagli vengono stampati sull'output standard.
RegEx create_from_string(pattern: String, show_error: bool = true) static 🔗
Crea e compila un nuovo oggetto RegEx. Vedi anche compile().
Restituisce il numero di gruppi di cattura nel modello compilato.
PackedStringArray get_names() const 🔗
Restituisce un array di nomi di gruppi di cattura denominati nel pattern compilato. Sono elencati in ordine di apparizione.
Restituisce il modello di ricerca originale compilato.
Restituisce se a questo oggetto è assegnato un modello di ricerca valido.
RegExMatch search(subject: String, offset: int = 0, end: int = -1) const 🔗
Ricerca nel testo il modello compilato. Restituisce un contenitore RegExMatch del primo risultato corrispondente se trovato, altrimenti null.
La regione in cui cercare può essere specificata con offset e end. Ciò è utile quando si cerca un'altra corrispondenza nello stesso soggetto (subject), richiamando questo metodo dopo un successo precedente. Nota che impostare questi parametri non è la stessa cosa di passare una stringa abbreviata. Ad esempio, l'ancora di inizio ^ non è influenzata da offset e il carattere prima di offset sarà controllato per il confine di parola \b.
Array[RegExMatch] search_all(subject: String, offset: int = 0, end: int = -1) const 🔗
Ricerca nel testo il modello compilato. Restituisce un array di contenitori RegExMatch per ogni risultato non sovrapposto. Se nessun risultato è stato trovato, viene restituito un array vuoto.
La regione in cui cercare può essere specificata con offset e end. Ciò è utile quando si cerca un'altra corrispondenza nello stesso soggetto (subject), richiamando questo metodo dopo un successo precedente. Nota che impostare questi parametri non è la stessa cosa di passare una stringa abbreviata. Ad esempio, l'ancora di inizio ^ non è influenzata da offset e il carattere prima di offset sarà controllato per il confine di parola \b.
String sub(subject: String, replacement: String, all: bool = false, offset: int = 0, end: int = -1) const 🔗
Ricerca nel testo il modello compilato e lo sostituisce con la stringa specificata. Escape e backreference come $1 e $name vengono espansi e risolti. Per impostazione predefinita, solo la prima istanza viene sostituita, ma può essere modificata per tutte le istanze (sostituzione globale).
La regione in cui cercare può essere specificata con offset e end. Ciò è utile quando si cerca un'altra corrispondenza nello stesso soggetto (subject), richiamando questo metodo dopo un successo precedente. Nota che impostare questi parametri non è la stessa cosa di passare una stringa abbreviata. Ad esempio, l'ancora di inizio ^ non è influenzata da offset e il carattere prima di offset sarà controllato per il confine di parola \b.