Path: blob/master/modules/regex/doc_classes/RegEx.xml
20897 views
<?xml version="1.0" encoding="UTF-8" ?>1<class name="RegEx" inherits="RefCounted" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">2<brief_description>3Class for searching text for patterns using regular expressions.4</brief_description>5<description>6A 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 [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet.7To begin, the RegEx object needs to be compiled with the search pattern using [method compile] before it can be used. Alternatively, the static method [method create_from_string] can be used to create and compile a RegEx object in a single method call.8[codeblock]9var regex = RegEx.new()10regex.compile("\\w-(\\d+)")11# Shorthand to create and compile a regex (used in the examples below):12var regex2 = RegEx.create_from_string("\\w-(\\d+)")13[/codeblock]14The search pattern must be escaped first for GDScript before it is escaped for the expression. For example, [code]compile("\\d+")[/code] would be read by RegEx as [code]\d+[/code]. Similarly, [code]compile("\"(?:\\\\.|[^\"])*\"")[/code] would be read as [code]"(?:\\.|[^"])*"[/code]. In GDScript, you can also use raw string literals (r-strings). For example, [code]compile(r'"(?:\\.|[^"])*"')[/code] would be read the same.15Using [method 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 [method RegExMatch.get_string] and [method RegExMatch.get_start].16[codeblock]17var regex = RegEx.create_from_string("\\w-(\\d+)")18var result = regex.search("abc n-0123")19if result:20print(result.get_string()) # Prints "n-0123"21[/codeblock]22The results of capturing groups [code]()[/code] 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 [code]result.get_string(1)[/code] would give you [code]0123[/code].23This 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.24[codeblock]25var regex = RegEx.create_from_string("d(?<digit>[0-9]+)|x(?<digit>[0-9a-f]+)")26var result = regex.search("the number is x2f")27if result:28print(result.get_string("digit")) # Prints "2f"29[/codeblock]30If you need to process multiple results, [method search_all] generates a list of all non-overlapping results. This can be combined with a [code]for[/code] loop for convenience.31[codeblock]32# Prints "01 03 0 3f 42"33for result in regex.search_all("d01, d03, d0c, x3f and x42"):34print(result.get_string("digit"))35[/codeblock]36[b]Example:[/b] Split a string using a RegEx:37[codeblock]38var regex = RegEx.create_from_string("\\S+") # Negated whitespace character class.39var results = []40for result in regex.search_all("One Two \n\tThree"):41results.push_back(result.get_string())42print(results) # Prints ["One", "Two", "Three"]43[/codeblock]44[b]Note:[/b] Godot's regex implementation is based on the [url=https://www.pcre.org/]PCRE2[/url] library. You can view the full pattern reference [url=https://www.pcre.org/current/doc/html/pcre2pattern.html]here[/url].45[b]Tip:[/b] You can use [url=https://regexr.com/]Regexr[/url] to test regular expressions online.46</description>47<tutorials>48</tutorials>49<methods>50<method name="clear">51<return type="void" />52<description>53This method resets the state of the object, as if it was freshly created. Namely, it unassigns the regular expression of this object.54</description>55</method>56<method name="compile">57<return type="int" enum="Error" />58<param index="0" name="pattern" type="String" />59<param index="1" name="show_error" type="bool" default="true" />60<description>61Compiles and assign the search pattern to use. Returns [constant OK] if the compilation is successful. If compilation fails, returns [constant FAILED] and when [param show_error] is [code]true[/code], details are printed to standard output.62</description>63</method>64<method name="create_from_string" qualifiers="static">65<return type="RegEx" />66<param index="0" name="pattern" type="String" />67<param index="1" name="show_error" type="bool" default="true" />68<description>69Creates and compiles a new [RegEx] object. See also [method compile].70</description>71</method>72<method name="get_group_count" qualifiers="const">73<return type="int" />74<description>75Returns the number of capturing groups in compiled pattern.76</description>77</method>78<method name="get_names" qualifiers="const">79<return type="PackedStringArray" />80<description>81Returns an array of names of named capturing groups in the compiled pattern. They are ordered by appearance.82</description>83</method>84<method name="get_pattern" qualifiers="const">85<return type="String" />86<description>87Returns the original search pattern that was compiled.88</description>89</method>90<method name="is_valid" qualifiers="const">91<return type="bool" />92<description>93Returns whether this object has a valid search pattern assigned.94</description>95</method>96<method name="search" qualifiers="const">97<return type="RegExMatch" />98<param index="0" name="subject" type="String" />99<param index="1" name="offset" type="int" default="0" />100<param index="2" name="end" type="int" default="-1" />101<description>102Searches the text for the compiled pattern. Returns a [RegExMatch] container of the first matching result if found, otherwise [code]null[/code].103The region to search within can be specified with [param offset] and [param end]. This is useful when searching for another match in the same [param 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 [code]^[/code] is not affected by [param offset], and the character before [param offset] will be checked for the word boundary [code]\b[/code].104</description>105</method>106<method name="search_all" qualifiers="const">107<return type="RegExMatch[]" />108<param index="0" name="subject" type="String" />109<param index="1" name="offset" type="int" default="0" />110<param index="2" name="end" type="int" default="-1" />111<description>112Searches 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.113The region to search within can be specified with [param offset] and [param end]. This is useful when searching for another match in the same [param 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 [code]^[/code] is not affected by [param offset], and the character before [param offset] will be checked for the word boundary [code]\b[/code].114</description>115</method>116<method name="sub" qualifiers="const">117<return type="String" />118<param index="0" name="subject" type="String" />119<param index="1" name="replacement" type="String" />120<param index="2" name="all" type="bool" default="false" />121<param index="3" name="offset" type="int" default="0" />122<param index="4" name="end" type="int" default="-1" />123<description>124Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as [code]$1[/code] and [code]$name[/code] are expanded and resolved. By default, only the first instance is replaced, but it can be changed for all instances (global replacement).125The region to search within can be specified with [param offset] and [param end]. This is useful when searching for another match in the same [param 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 [code]^[/code] is not affected by [param offset], and the character before [param offset] will be checked for the word boundary [code]\b[/code].126</description>127</method>128</methods>129</class>130131132