Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Str.subst: Add examples for nth(*), etc. #3460

Merged
merged 1 commit into from
Jun 6, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 16 additions & 7 deletions doc/Type/Str.pod6
Original file line number Diff line number Diff line change
Expand Up @@ -823,14 +823,23 @@ regex, not the C<subst> method call.
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(/\s+/, :g); # global substitution - returns Heyfoofoofoo

$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
say $str.subst(/foo/, "bar", :g); # OUTPUT: «Hey bar bar bar␤»
say $str.subst(/\s+/, :g); # OUTPUT: «Heyfoofoofoo␤»

say $str.subst(/foo/, "bar", :x(0)); # OUTPUT: «Hey foo foo foo␤»
say $str.subst(/foo/, "bar", :x(1)); # OUTPUT: «Hey bar foo foo␤»
# Can not match 4 times, so no substitutions made
say $str.subst(/foo/, "bar", :x(4)); # OUTPUT: «Hey foo foo foo␤»
say $str.subst(/foo/, "bar", :x(2..4)); # OUTPUT: «Hey bar bar bar␤»
# Replace all of them, identical to :g
say $str.subst(/foo/, "bar", :x(*)); # OUTPUT: «Hey bar bar bar␤»

say $str.subst(/foo/, "bar", :nth(3)); # OUTPUT: «Hey foo foo bar␤»
# Replace last match
say $str.subst(/foo/, "bar", :nth(*)); # OUTPUT: «Hey foo foo bar␤»
# Replace next-to-last last match
say $str.subst(/foo/, "bar", :nth(*-1)); # OUTPUT: «Hey foo bar foo␤»

The C<:nth> adverb has readable English-looking variants:

Expand Down