RegEx
Наследует: RefCounted < Object
Класс для поиска в тексте шаблонов с использованием регулярных выражений.
Описание
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.
Методы
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 |
Описания метода
void clear() 🔗
Этот метод сбрасывает состояние объекта, как будто он был только что создан. А именно, он отменяет назначение регулярного выражения этому объекту.
Error compile(pattern: String, show_error: bool = true) 🔗
Компилирует и назначает шаблон поиска для использования. Возвращает @GlobalScope.OK, если компиляция прошла успешно. Если компиляция не удалась, возвращает @GlobalScope.FAILED, а когда show_error равен true, подробности выводятся на стандартный вывод.
RegEx create_from_string(pattern: String, show_error: bool = true) static 🔗
Создает и компилирует новый объект RegEx. См. также compile().
Возвращает количество групп захвата в скомпилированном шаблоне.
PackedStringArray get_names() const 🔗
Возвращает массив имен именованных групп захвата в скомпилированном шаблоне. Они упорядочены по внешнему виду.
Возвращает исходный шаблон поиска, который был скомпилирован.
Возвращает, назначен ли этому объекту допустимый шаблон поиска.
RegExMatch search(subject: String, offset: int = 0, end: int = -1) const 🔗
Выполняет поиск скомпилированного шаблона в тексте. Возвращает контейнер RegExMatch первого совпадающего результата, если он найден, в противном случае null.
Область поиска можно указать с помощью offset и end. Это полезно при поиске другого совпадения в том же subject путем повторного вызова этого метода после предыдущего успешного выполнения. Обратите внимание, что установка этих параметров отличается от передачи сокращенной строки. Например, начальный якорь ^ не зависит от offset, а символ перед offset будет проверяться на границу слова \b.
Array[RegExMatch] search_all(subject: String, offset: int = 0, end: int = -1) const 🔗
Выполняет поиск скомпилированного шаблона в тексте. Возвращает массив контейнеров RegExMatch для каждого неперекрывающегося результата. Если результаты не найдены, вместо этого возвращается пустой массив.
Область для поиска можно указать с помощью offset и end. Это полезно при поиске другого совпадения в том же subject путем повторного вызова этого метода после предыдущего успешного выполнения. Обратите внимание, что установка этих параметров отличается от передачи сокращенной строки. Например, начальный якорь ^ не зависит от offset, а символ перед offset будет проверяться на границу слова \b.
String sub(subject: String, replacement: String, all: bool = false, offset: int = 0, end: int = -1) const 🔗
Выполняет поиск скомпилированного шаблона в тексте и заменяет его указанной строкой. Экранированные символы и обратные ссылки, такие как $1 и $name, раскрываются и разрешаются. По умолчанию заменяется только первый экземпляр, но его можно изменить для всех экземпляров (глобальная замена).
Область поиска можно указать с помощью offset и end. Это полезно при поиске другого совпадения в том же subject путем повторного вызова этого метода после предыдущего успешного выполнения. Обратите внимание, что установка этих параметров отличается от передачи сокращенной строки. Например, начальный якорь ^ не зависит от offset, а символ перед offset будет проверяться на границу слова \b.