Core Function Regex Replace

From Sputnik Wiki
Jump to: navigation, search
<Expression> =~ s/pattern/replacement/flags
s/pattern/replacement/flags

Contents

Description

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.

pattern

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 Eval().

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

Default: None of the flags are used by default.

Return Value

Success: Returns the modified string.

Failure: Returns an empty string.

Remarks

See <Expression> =~ m/pattern/flags for details on Regexp and how to use them.

Example

Replacement on an array

# Make array
$test = array("Cat111", "Dog222", "Fox333");
 
# Remove all numbers from array
$test =~ s/\d+//g;
 
# Print result
printr($test);
# Prints:
# ARRAY
# {
#         [0] => Cat
#         [1] => Dog
#         [2] => Fox
# }

Replacement on an array keys

# Make array
$test = array("Cat111" => "Meow", "Dog222" => "Woof");
 
# Remove all numbers from array
$test =~ s/\d+//gv;
 
# Print result
printr($test);
# Prints:
# ARRAY
# {
#         [Cat] => Meow
#         [Dog] => Woof
# }

A simple search replace

// A string to use
$var = "That cat is cute but this cat is not";
 
// Replace cat with dog
$var =~ s/cat/dog/;
 
println( $var );

Same again but this time replace all using the "g" switch

// A string to use
$var = "That cat is cute but this cat is not";
 
// Replace cat with dog
$var =~ s/cat/dog/g;
 
println( $var );

Same again but this time ignore case using the "i" switch

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

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

// A string to use
$var =  "One=100\n";
$var .= "Two=200\n";
$var .= "Three=300\n";
 
$var =~ s/(\w+)=(\w+)/$2=$1/gi;
 
println( $var );

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

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

Execute the replace as a function using the "e" switch 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
$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;
 
println( $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
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 floor()

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

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

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

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

Function StrToHex ( $Str )  
{
	$Str = unpack('H*', $Str, 3);
	# Operationally convert the hex characters
	# to upper case
	$Str =~ tr/a-z/A-Z/;
	return $Str;
}
Function HexToStr ( $Hex )
{
	$Hex =~ s/([\dA-Fa-f][\dA-Fa-f])/pack("C", dec($1))/eg;
	return $Hex;
}
my $Hex = StrToHex("Hello world!");
echo "Hex: $Hex\n";
my $Str = HexToStr($Hex);
echo "Str: $Str\n";

Here we use regex to decode a QUERY_STRING and resolve the key, values into a hashmap Request[]

Global $Request = array();
{
	$QueryString = EnvGet("QUERY_STRING");
	$QueryList = Split($QueryString, '&');
	Foreach($QueryList as $i)
	{
		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;
	}
}

Example of using /x flag

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;
print( $a );

Example of using /r 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"
echo "OLD: $old\n"; //Prints: cat
echo "NEW: $new\n"; //Prints: dog

If you ignore the $var =~ part and just do the regex part it will use the $_ variable example

my $_ = "cat";
s/cat/dog/;
say $_; // Prints dog
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox