Regular Expressions in UnrealScript

Regular expressions are a powerful tool for pattern matching and manipulation of strings. UnrealScript provides built-in support for regular expressions through the Rx class. Let’s explore some common regexp-related tasks in UnrealScript.

class RegexExample extends Object;

function Init()
{
    local Rx Regex;
    local array<string> Matches;
    local string Input, Result;
    local int i;

    // Test if a pattern matches a string
    if (class'Rx'.static.Test("p([a-z]+)ch", "peach"))
    {
        `log("Match found");
    }

    // Compile a regex pattern
    Regex = class'Rx'.static.Create("p([a-z]+)ch");

    // Find the first match
    Input = "peach punch";
    if (Regex.Find(Input, Matches))
    {
        `log("Found match:" @ Matches[0]);
    }

    // Find all matches
    Input = "peach punch pinch";
    if (Regex.FindAll(Input, Matches))
    {
        `log("All matches:");
        for (i = 0; i < Matches.Length; i++)
        {
            `log(Matches[i]);
        }
    }

    // Replace matches
    Input = "a peach";
    Result = Regex.Replace(Input, "<fruit>");
    `log("Replaced:" @ Result);

    // Using a callback function for replacement
    Result = Regex.Replace(Input, ReplaceCallback);
    `log("Replaced with callback:" @ Result);
}

function string ReplaceCallback(string Match)
{
    return Caps(Match);
}

Let’s break down the key parts of this code:

  1. We use class'Rx'.static.Test() to check if a pattern matches a string.

  2. To perform more complex operations, we create a compiled regex object using class'Rx'.static.Create().

  3. The Find() method finds the first match in a string.

  4. FindAll() finds all matches in a string.

  5. We can use Replace() to replace matches with a new string.

  6. For more complex replacements, we can use a callback function with Replace().

Note that UnrealScript’s regex implementation may have some limitations compared to more robust regex libraries in other languages. Always refer to the UnrealScript documentation for the most up-to-date information on regex capabilities.

To use this code, you would typically call the Init() function from your game’s initialization process or from another appropriate location in your UnrealScript code.

Remember that UnrealScript’s regex functionality might not be as extensive as what’s available in some other languages, so you may need to adjust your regex patterns or find alternative solutions for more complex use cases.