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.

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()

Error

compile(pattern: String, show_error: bool = true)

RegEx

create_from_string(pattern: String, show_error: bool = true) static

int

get_group_count() const

PackedStringArray

get_names() const

String

get_pattern() const

bool

is_valid() const

RegExMatch

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

Array[RegExMatch]

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

String

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) 🔗

Compiles and assign the search pattern to use. Returns @GlobalScope.OK if the compilation is successful. If compilation fails, returns @GlobalScope.FAILED and when show_error is true, details are printed to standard output.


RegEx create_from_string(pattern: String, show_error: bool = true) static 🔗

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


int get_group_count() const 🔗

返回編譯模式中捕獲組的數量。


PackedStringArray get_names() const 🔗

返回一個陣列,該陣列是編譯模式中命名的捕獲組的名稱。它們是按外觀排序的。


String get_pattern() const 🔗

返回被編譯的原始搜索模式。


bool is_valid() const 🔗

返回此物件是否分配了有效的搜索模式。


在文字中搜索編譯後的模式。如果找到,則將首個配對結果放在 RegExMatch 容器中返回,否則返回 null

可以使用 offsetend 指定要搜索的區域。這對在上一次成功後再次呼叫該方法,以相同的 subject 搜索另一個配對項時很有用。請注意,設定這些參數不同於傳遞縮短後的字串。例如,起始錨點 ^ 不受 offset 的影響,會為單詞邊界 \b 檢查 offset 之前的字符。


Array[RegExMatch] search_all(subject: String, offset: int = 0, end: int = -1) const 🔗

在文字中搜索編譯後的模式。返回 RegExMatch 容器的陣列,其中每個容器包含的是互不重疊的配對結果。如果沒有找到結果,則返回一個空陣列。

可以使用 offsetend 指定要搜索的區域。這對在上一次成功後再次呼叫該方法,以相同的 subject 搜索另一個配對項時很有用。請注意,設定這些參數不同於傳遞縮短後的字串。例如,起始錨點 ^ 不受 offset 的影響,會為單詞邊界 \b 檢查 offset 之前的字符。


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

在文字中搜索編譯後的模式,並將其替換為指定的字串。諸如 $1$name 等轉義和反向引用會被擴充和解析。預設情況下,只有第一個實例被替換,但可以修改為針對所有實例(全域替換)。

可以使用 offsetend 指定要搜索的區域。這對在上一次成功後再次呼叫該方法,以相同的 subject 搜索另一個配對項時很有用。請注意,設定這些參數不同於傳遞縮短後的字串。例如,起始錨點 ^ 不受 offset 的影響,會為單詞邊界 \b 檢查 offset 之前的字符。