RegEx

    Category: Core

    Class for searching text for patterns using regular expressions.

    Regular Expression (or regex) is a compact programming 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 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 before it can be used.

    The search pattern must be escaped first for gdscript before it is escaped for the expression. For example, would be read by RegEx as \d+. Similarly, compile("\"(?:\\\\.|[^\"])*\"") would be read as "(?:\\.|[^"])*"

    The results of capturing groups can be retrieved by passing the group number to the various functions in RegExMatch. Group 0 is the default and would 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.

    If you need to process multiple results, generates a list of all non-overlapping results. This can be combined with a for-loop for convenience.

    • void clear ( )

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


    • Error compile ( pattern )

    Compiles and assign the search pattern to use. Returns OK if the compilation is successful. If an error is encountered the details are printed to STDOUT and FAILED is returned.


    • int get_group_count ( ) const

    Returns an array of names of named capturing groups in the compiled pattern. They are ordered by appearance.


    • get_pattern ( ) const

    Returns the original search pattern that was compiled.


    • bool is_valid ( ) const

    Returns whether this object has a valid search pattern assigned.


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

    Searches the text for the compiled pattern. Returns a container of the first matching result 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. Returns an array of RegExMatch containers for each non-overlapping result. If no results were found an empty array is returned instead. The region to search within can be specified without modifying where the start and end anchor would be.


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