Core Function Regex Replace

From Sputnik Wiki
Revision as of 15:22, 1 December 2011 by UberFoX (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
<Expression> =~ 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 is a string.

pattern

The regular expression pattern to match.

pattern

A string to replace the matche(s) 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 occurances of the pattern in the string (Default is only match the first).

e = Treat the replace string as actual Sputnik code similar to Eval().

Return Value

Success: Returns the modified string.

Failure: Returns an empty string.

Remarks

See regex match for details on regex.

Example

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

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

$hex = Unpack("*H", "Hello World!", 1);
println("Hex String: " . $hex);
$hex =~ s/([\dA-Fa-f][\dA-Fa-f])/Chr(Dec($1))/ego;
println("Normal String: " . $hex);
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox