Curiosity: unglobal first-only replace()?

More a curiosity than a problem. julia’s replace is global. Perl requires the ‘g’ modifier to do a global replace.

my $s= "aabbccddaabbccddaabbccdd";
$s =~ s/(b+)/[$1]/;
print "$s\n";

replaces only the first match:

aa[bb]ccddaabbccddaabbccdd

Julia replaces all matches, because this is what replace does by default:

julia> replace("aabbccddaaabbbcccdddaabbccdd", r"(b+)", s"[\1]")
"aa[bb]ccddaaa[bbb]cccdddaa[bb]ccdd"

is there a built-in for first-only replacements, or do I program this?

/iaw

Julia v0.6:

julia> replace("aabbccddaaabbbcccdddaabbccdd", r"(b+)", s"[\1]", 1)
"aa[bb]ccddaaabbbcccdddaabbccdd"

Julia v0.7:

julia> replace("aabbccddaaabbbcccdddaabbccdd", r"(b+)" => s"[\1]", count = 1)
"aa[bb]ccddaaabbbcccdddaabbccdd"

It is also mentioned in the manual for replace (check ?replace in the REPL).

2 Likes