Regular Expressions in AngelScript

Our first example demonstrates how to use regular expressions in AngelScript. Here’s the full source code:

// Import necessary modules
import string;
import regex;

void main()
{
    // This tests whether a pattern matches a string.
    bool match = regex::match("p([a-z]+)ch", "peach");
    print(match ? "true" : "false");

    // For other regex tasks, we'll need to create a Regex object.
    Regex@ r = regex::compile("p([a-z]+)ch");

    // Many methods are available on this object. Here's a match test like we saw earlier.
    print(r.match("peach") ? "true" : "false");

    // This finds the match for the regex.
    string result = r.search("peach punch");
    print(result);

    // This also finds the first match but returns the start and end indexes for the match.
    array<int> indices = r.search("peach punch", regex::CAPTURE_FIRST);
    print("idx: [" + indices[0] + " " + indices[1] + "]");

    // The capture variants include information about both the whole-pattern matches and the submatches.
    array<string> captures = r.capture("peach punch");
    print("[" + captures[0] + " " + captures[1] + "]");

    // To find all matches for a regex:
    array<string> allMatches = r.search("peach punch pinch", regex::GLOBAL);
    print("[" + join(allMatches, " ") + "]");

    // The replace function can be used to replace subsets of strings with other values.
    string replaced = r.replace("a peach", "<fruit>");
    print(replaced);

    // AngelScript doesn't have a direct equivalent to ReplaceAllFunc, but you can achieve similar results with a custom function.
    string input = "a peach";
    string output = r.replace(input, function(const string &in s) { return s.toupper(); });
    print(output);
}

string join(const array<string> &in arr, const string &in delimiter)
{
    string result = "";
    for (uint i = 0; i < arr.length(); i++)
    {
        if (i > 0) result += delimiter;
        result += arr[i];
    }
    return result;
}

To run the program, save the code in a file with a .as extension and use your AngelScript interpreter to execute it.

$ angelscript regular-expressions.as
true
true
peach
idx: [0 5]
[peach ea]
[peach punch pinch]
a <fruit>
a PEACH

This example demonstrates basic usage of regular expressions in AngelScript. Note that the exact syntax and available methods may vary depending on the specific regex implementation used in your AngelScript environment.

For a complete reference on AngelScript regular expressions, check the documentation for the regex module in your AngelScript implementation.