Documentation for method subst

Documentation for method subst, assembled from the following types:

class Str

From Str

(Str) method subst

multi method subst(Str:D: $matcher$replacement*%opts)

Returns the invocant string where $matcher is replaced by $replacement (or the original string, if no match was found).

There is an in-place syntactic variant of subst spelled s/matcher/replacement/.

$matcher can be a Regex, or a literal Str. Non-Str matcher arguments of type Cool are coerced to Str for literal matching.

Literal replacement substitution

my $some-string = "Some foo";
my $another-string = $some-string.subst(/foo/"string"); # gives 'Some string' 
$some-string.=subst(/foo/"string"); # in-place substitution. $some-string is now 'Some string' 


The replacement can be a closure:

my $i = 41;
my $str = "The answer is secret.";
my $real-answer = $str.subst(/secret/{++$i}); # The answer to everything 


If you are going to use captures, you have to use a closure like so:

say 'abc123defg'.subst(/(\d+)/{ " before $0 after " })
# OUTPUT: «abc before 123 after defg␤» 

More Examples

Here are other examples of usage:

my $str = "Hey foo foo foo";
$str.subst(/foo/"bar":g); # global substitution - returns Hey bar bar bar 
$str.subst(/foo/"no subst":x(0)); # targeted substitution. Number of times to substitute. Returns back unmodified. 
$str.subst(/foo/"bar":x(1)); #replace just the first occurrence. 
$str.subst(/foo/"bar":nth(3)); # replace nth match alone. Replaces the third foo. Returns Hey foo foo bar 

The :nth adverb has readable English-looking variants:

say 'ooooo'.subst: 'o''x':1st; # OUTPUT: «xoooo␤» 
say 'ooooo'.subst: 'o''x':2nd; # OUTPUT: «oxooo␤» 
say 'ooooo'.subst: 'o''x':3rd; # OUTPUT: «ooxoo␤» 
say 'ooooo'.subst: 'o''x':4th; # OUTPUT: «oooxo␤» 


The following adverbs are supported

short long meaning
:g :global tries to match as often as possible
:nth(Int|Callable|Whatever) only substitute the nth match; aliases: :st, :nd, :rd, and :th
:ss :samespace preserves whitespace on substitution
:ii :samecase preserves case on substitution
:mm :samemark preserves character marks (e.g. 'ü' replaced with 'o' will result in 'ö')
:x(Int|Range|Whatever) substitute exactly $x matches

Note that only in the s/// form :ii implies :i and :ss implies :s. In the method form, the :s and :i modifiers must be added to the regex, not the subst method call.