Skip to reading
GDScript Programming & Godot

14. Strings, formatting and regular expressions

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page
Code example
func run() -> Array:
    var answer: String = "  Open The Door  ".strip_edges().to_lower()
    var words: PackedStringArray = answer.split(" ", false)
    var tidied: String = " ".join(words)
    var caption: String = "%s: %d" % ["Score", 25]
    return [tidied, caption, answer.contains("door")]

String methods include to_lower, to_upper, strip_edges, contains, begins_with, ends_with, replace, split, join, substr, left, right and length. Use substr(start, length) to extract a portion. A negative length means to the end.

Code example
func run() -> String:
    var expression := RegEx.new()
    var error_code: Error = expression.compile("([A-Z]+)-(\\d+)")
    if error_code != OK:
        return "Bad pattern"
    var found: RegExMatch = expression.search("KEY-204")
    return found.get_string(2) if found != null else "No match"

Native RegEx returns RegExMatch objects. PCA’s native RegexSearch helper also returns RegExMatch, which differs from PCA Script’s dictionary-shaped regex result. Use get_string, get_start and get_end on a match.

Page 22 of 378Permalink
Go to page