RegEx

Inherits: Reference < Object

Clase para buscar patrones en el texto usando expresiones regulares.

Descripción

A regular expression (or regex) is a compact language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For instance, 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.

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 "(?:\\.|[^"])*".

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.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, search_all 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.

Métodos

void

clear ( )

Error

compile ( String pattern )

int

get_group_count ( ) const

Array

get_names ( ) const

String

get_pattern ( ) const

bool

is_valid ( ) const

RegExMatch

search ( String subject, int offset=0, int end=-1 ) const

Array

search_all ( String subject, int offset=0, int end=-1 ) const

String

sub ( String subject, String replacement, bool all=false, int offset=0, int end=-1 ) const

Descripciones de Métodos

  • void clear ( )

Este método restablece el estado del objeto, como si fuera recién creado. Es decir, desasigna la expresión regular de este objeto.


Compila y asigna el patrón de búsqueda a utilizar. Devuelve @GlobalScope.OK si la compilación tiene éxito. Si se encuentra un error, los detalles se imprimen en la salida estándar y se devuelve un error.


  • int get_group_count ( ) const

Devuelve el número de grupos de captura en un patrón compilado.


  • Array get_names ( ) const

Devuelve un array de nombres de grupos de captura de nombres en el patrón compilado. Están ordenados por su apariencia.


  • String get_pattern ( ) const

Devuelve el patrón de búsqueda original que fue compilado.


  • bool is_valid ( ) const

Devuelve si este objeto tiene asignado un patrón de búsqueda válido.


Busca en el texto el patrón compilado. Devuelve un contenedor RegExMatch del primer resultado coincidente si se encuentra, de lo contrario null. La región en la que se debe buscar puede especificarse sin modificar el lugar en el que se encuentra el anclaje de inicio y fin.


Busca en el texto el patrón compilado. Devuelve un array de contenedores RegExMatch para cada resultado no superpuesto. Si no se encuentran resultados, se devuelve un array vacío. La región en la que se debe buscar puede ser especificada sin modificar el lugar donde se encuentran el ancla de inicio y el ancla de fin.


Busca en el texto el patrón compilado y lo reemplaza con la string especificada. Escapadas y retro-referencias como $1 y $name son expandidas y resueltas. Por defecto, sólo se reemplaza la primera instancia, pero se puede cambiar para todas las instancias (reemplazo global). La región en la que se debe buscar puede especificarse sin modificar el lugar en el que se encuentra el ancla de inicio y fin.