"Sputnik" help  
Sputnik Help
<expression> =~ s/pattern/replacement/flags
s/pattern/replacement/flags

Description

Sputnik features a powerful set of regular expression features built into the core language.

This operator will Replace parts of a string using a regular expression pattern and optionally executing functions on the matched groups.

Replace parts of a string using a regular expression pattern and optionally executing functions on the matched groups.

Parameters

<expression> Any valid expression that can be used usually a string but it will accept an array and do the Regexp replacement on every item in the array (it is recursive and will do every array in the array and so on).

You may choose to skip this part and it will use @_ for you.

pattern

The regular expression pattern to match.

replacement A string to replace the match(es) with.
flags

Optional; The flags to use in the pattern.

i = Ignore case.
m = Treat the string as multiple lines.
s = Treat the string as a single line.
o = Do not recompile the regular expression after the first compile (Improves speed of your matches if you run the pattern many times).
g = Match all occurrences of the pattern in the string (Default is only match the first).
e = Treat the replace string as actual Sputnik code similar to {} in a normal string.
t = By default, the regular expression engine searches from left to right. You can reverse the search direction by using this flag.
r = Non-destructive causes the variable to not be modified but the result to still be returned as normal.
n = Do not capture unnamed groups. The only valid captures are explicitly named or numbered groups of the form (?<name> subexpression)
v = Do replacement on array keys instead of values (it will only use string keys not numeric keys).
c = Ignore cultural differences in language.
p = Do not parse the Regexp SEARCH pattern for variables etc.
P = Do not parse the Regexp REPLACE pattern for variables etc.
x = Allows newlines and comments and ignores whitespace (Regex comment is #)

Note - The flags are case sensitive.

Default: None of the flags are used by default.

Return Value

Success: Returns the modified string.
Failure: Returns an empty string.

Remarks

Go read Regular Expressions to learn important information you need to know to use this operator properly.

Sputnik introduces a powerful string manipulation feature with its s/// syntax for regex replacing. This syntax allows you to perform search and replace operations using regular expressions, enabling you to modify strings with precision and flexibility.

The s/// syntax follows a pattern similar to other popular programming languages, providing a concise and intuitive way to perform string substitutions. By specifying a search pattern, replacement text, and optional flags, you can define complex substitution rules to transform strings according to your needs.

This feature leverages the power of regular expressions, which are a widely-used tool for pattern matching and text manipulation. With the s/// syntax, you can easily find specific patterns within a string and substitute them with desired content, whether it's a literal replacement or dynamically generated text.

The ability to use regular expressions for string replacement gives you fine-grained control over the transformation process. You can perform simple substitutions, global replacements, case-insensitive matching, and many other advanced operations using regular expression modifiers and flags.

The s/// syntax in Sputnik provides a versatile and efficient way to manipulate strings, making it easier to perform complex text transformations. Whether you need to perform basic find-and-replace operations or intricate pattern matching, the s/// syntax empowers you to accomplish these tasks with elegance and ease.

Related

Regex Match, RexMatch, RexReplace, RexRef

Example

A simple search replace:

// A string to use
my $var = "That cat is cute but this cat is not";
 // Replace cat with dog
$var =~ s/cat/dog/;
say $var;
// PRINTS
// That dog is cute but this cat is not

Same again but this time replace all using the "g" flag:

// A string to use
my $var = "That cat is cute but this cat is not";
 // Replace cat with dog
$var =~ s/cat/dog/g;
say $var;
// PRINTS
// That dog is cute but this dog is not

Same again but this time ignore case using the "i" flag:

// A string to use
my $var = "That cat is cute but this Cat is not";
 // Replace cat with dog
$var =~ s/cat/dog/gi;
say $var;
// PRINTS
// That dog is cute but this dog is not

Search the string and reverse the order so stuff after the = now comes before it:

my $var = "One=100\n";
$var .= "Two=200\n";
$var .= "Three=300\n"; 
$var =~ s/(\w+)=(\w+)/$2=$1/gi; 
say $var;
// PRINTS
// 100=One
// 200=Two
// 300=Three

Execute the replace as a function using the "e" flag and increase all numbers in the string by 1:

// A string to use
my $var =  "10 20 30 40 50 60 70 80 90 100";
$var =~ s/(\d+)/++$1/egi;
say $var;
// PRINTS
// 11 21 31 41 51 61 71 81 91 101

Execute the replace as a function using the "e" flag and increase all numbers in the string by 1 and move all the letters to the end instead of beginning of each section:

// A string to use
my $var =  "A:10 B:20 C:30 D:40 E:50 F:60 G:70 H:80 I:90 J:100";
$var =~ s/(\w):(\d+)/Action($1, $2)/egi; 
say $var;
// PRINTS
// 11:A 21:B 31:C 41:D 51:E 61:F 71:G 81:H 91:I 101:J
 
// Define a function to use for the regex
// this is our callback function
Function Action($Letter, $Number)
{
    // Move to letter to end and increase the number by 1
    return ++$Number . ":" . $Letter;
}

Take a string containing floating point numbers and convert them to integers using the Floor() function:

// A string to use
my $var =  "10.2 300.45 133.77";
$var =~ s/(\d+\.\d*)/floor($1)/egi; 
say $var;
// PRINTS
// 10 300 133

Convert a string to hex and back again using flag"e" on a regex to decode the hex:

my $str = "Hello World!";
say "Orig String: " . $str;
$str =~ s/(.)/Hex(AscW($1), 2)/ego;
say "Hex String: " . $str;
$str =~ s/([\dA-Fa-f][\dA-Fa-f])/ChrW(Dec($1))/ego;
say "Normal String: " . $str;
// PRINTS
// Orig String: Hello World!
// Hex String: 48656C6C6F20576F726C6421
// Normal String: Hello World!

Convert a string to hex and back again (another way to do it):

Function myStr2Hex ( $Str )  
{
    $Str = unpack("H*", $Str, 3);
    // Operationally convert the hex characters
    // to upper case
    $Str =~ tr/a-z/A-Z/;
    return $Str;
}
Function myHex2Str ( $Hex )
{
    $Hex =~ s/([\dA-Fa-f][\dA-Fa-f])/pack("C", dec($1))/eg;
    return $Hex;
}
my $Hex = myStr2Hex("Hello world!");
say "Hex: $Hex";
my $Str = myHex2Str($Hex);
say "Str: $Str";
// PRINTS
// Hex: 48656C6C6F20776F726C6421
// Str: Hello world!
Here we use regex to decode a HTML query string and resolve the key, values into an array called $Request:
// Create a query string for demonstration purposes
my $query = "ToDo=CreateAccount&Name=Admin&Password=1337";
// Assign the query to the environment
EnvSet("QUERY_STRING", $query);

// The code that creates the $Request array
Global $Request = array();
{
    $QueryString = EnvGet("QUERY_STRING");
    $QueryList = Split($QueryString, '&');
    Foreach(my $i in $QueryList)
    {
        my List ( $Key, $Value ) = Split($i, "=");
        $Value =~ s/%([a-fA-F0-9][a-fA-F0-9])/Chr(Dec($1))/ego;
        $Value =~ s/\+/ /gi; 
        $Value =~ s/\</&lt;/gi; 
        $Value =~ s/\>/&gt;/gi; 
        $Request[$Key] = $Value;
    }
}

// Print the result:
printr $Request;
// PRINTS
// Array
// (
//     [ToDo] => CreateAccount
//     [Name] => Admin
//     [Password] => 1337
// )

Example of using /x flag so you can use whitespace in the pattern and even add comments:

my $a = "xor eax, edx";
$a =~ s/
        \w+ # You can add comments
        \s*
        (\w+)
        \s* # Yup comments all over
        ,
        \s*
        (\w+)
        /lea $2, $1/x;
say $a;
// PRINTS
// lea edx, eax

Example of using /r flag that copies the input variable, carries out the substitution on the copy, and returns the result. The original remains unmodified:

my $old = "cat";
my $new = $old =~ s/cat/dog/r;
// $old is "cat" and $new is "dog"
say "OLD: $old"; // Prints: cat
say "NEW: $new"; // Prints: dog

If you ignore the $var =~ part and just do the regex part it will use the @_variable example:

@_ = "cat";
s/cat/dog/;
say @_; // Prints dog

Replacement on an array:

// Make array
my $array = array("Cat111", "Dog222", "Fox333");
// Remove all numbers from array
$array =~ s/\d+//g;
// Print result
printr($array);
// PRINTS
// Array
// (
//     [0] => Cat
//     [1] => Dog
//     [2] => Fox
// )

Replacement on an array keys using the "v" flag:

// Make array
my $array = array("Cat111" => "Meow", "Dog222" => "Woof");
// Remove all numbers from array
$array =~ s/\d+//gv;
// Print result
printr($array);
// PRINTS
// Array
// (
//     [Cat] => Meow
//     [Dog] => Woof
// )

 


Contact
Cheryl (uberfox@hotmail.com)
Homepage
http://ubersoft.org