RegEx

Inherits: Reference < Object

Category: Core

Brief Description

Simple regular expression matcher.

Member Functions

void clear ( )
int 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=null ) const
String sub ( String subject, String replacement, bool all=false, int offset=null, int end=null ) const

Description

Class for finding text patterns in a string using regular expressions. It can not perform replacements. Regular expressions are a way to define patterns of text to be searched. Details on writing patterns are too long to explain here but the Internet is full of tutorials and detailed explanations.

Once created, the RegEx object needs to be compiled with the pattern before it can be used. The pattern must be escaped first for gdscript before it is escaped for the expression. For example:

var exp = RegEx.new()

exp.compile("\\d+")

would be read by RegEx as \d+

Similarly:

exp.compile("\"(?:\\\\.|[^\"])\*\"")

would be read as "(?:\\.|[^"])\*"

Currently supported features:

* Capturing () and non-capturing (?:) groups

* Named capturing groups (?P<name>)

* Any character .

* Shorthand character classes \w \W \s \S \d \D

* User-defined character classes such as [A-Za-z]

* Simple quantifiers ?, \* and +

* Range quantifiers {x,y}

* Lazy (non-greedy) quantifiers \*?

* Beginning ^ and end $ anchors

* Alternation |

* Backreferences \1, \g{1}, and \g<name>

* POSIX character classes [[:alnum:]]

* Lookahead (?=), (?!) and lookbehind (?<=), (?<!)

* ASCII \xFF and Unicode \uFFFF code points (in a style similar to Python)

* Word boundaries \b, \B

Member Function Description

  • void clear ( )

This method resets the state of the object, as it was freshly created. Namely, it unassigns the regular expression of this object.

Compiles and assign the regular expression pattern to use.

  • int get_group_count ( ) const

Returns the number of numeric capturing groups.

  • Array get_names ( ) const

Returns an array of names of named capturing groups.

  • String get_pattern ( ) const

Returns the expression used to compile the code.

  • bool is_valid ( ) const

Returns whether this object has a valid regular expression assigned.

Searches the text for the compiled pattern. Returns a RegExMatch container of the first matching reult if found, otherwise null. The region to search within can be specified without modifying where the start and end anchor would be.

Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as \1 and \g<name> expanded and resolved. By default only the first instance is replaced but it can be changed for all instances (global replacement). The region to search within can be specified without modifying where the start and end anchor would be.