(Str) 方法 subst
subst 取的是單詞 substitution(替換)的前5個(gè)字符, 意為替換之意水醋。
multi method subst(Str:D: $matcher, $replacement, *%opts)
返回被調(diào)用的那個(gè)字符串, 其中 $matcher
被 $replacement
給替換掉了(或者返回原來的字符串, 如果沒有找到匹配的話)纺酸。
subst
有一個(gè)「就地」替換的句法變體, 它被拼寫為 s/matcher/replacement/
峰弹。
$matcher
可以是一個(gè)正則表達(dá)式, 或者一個(gè)字符串字面值。 Cool
類型的非字符串 matcher 會被強(qiáng)轉(zhuǎn)為字符串以用于字面上的匹配滥朱。
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'
replacement
可以是一個(gè)閉包:
my $i = 41;
my $str = "The answer is secret.";
my $real-answer = $str.subst(/secret/, {++$i}); # The answer to everything
下面是 subst 其它用法的例子:
my $str = "Hey foo foo foo";
$str.subst(/foo/, "bar", :g); # 全局替換 - 返回 Hey bar bar bar
$str.subst(/foo/, "no subst", :x(0)); # 有針對性的替換妆兑。要替換的次數(shù). 返回未修改過的字符串.
$str.subst(/foo/, "bar", :x(1)); # 只替換第一次出現(xiàn)。
$str.subst(/foo/, "bar", :nth(3)); # 單獨(dú)替換第 n 個(gè)匹配. 替換第三個(gè) foo. 返回 Hey foo foo bar
第三個(gè)參數(shù)傳遞給散列, 例如 :g
被吞噬參數(shù) *%opts
接收, 意為 g => True
苏携。
其中的 :nth
副詞擁有可讀的長得像英語那樣的變體:
say 'ooooo'.subst: 'o', 'x', :1st; # xoooo
say 'ooooo'.subst: 'o', 'x', :2nd; # oxooo
say 'ooooo'.subst: 'o', 'x', :3rd; # ooxoo
say 'ooooo'.subst: 'o', 'x', :4th; # oooxo
subst 還支持下面的副詞:
short | long | meaning |
---|---|---|
:g | :global | 盡可能多次地替換 |
:nth(Int|Callable) | 只替換第n次匹配; 別名: :st, :nd, :rd, 和 :th | |
:ss | :samespace | preserves whitespace on substitution |
:ii | :samecase | 替換時(shí)保留大小寫 |
:mm | :samemark | 保留字符標(biāo)記(e.g. 'ü' replaced with 'o' 會導(dǎo)致 '?') |
:x(Int|Callable) | substitute exactly $x matches |
注意, 只有在
s///
形式中:ii
暗指:i
而:ss
暗指:s
. 在方法的形式中:s
和:i
修飾符必須添加到正則表達(dá)式中, 而非添加到 subst 方法調(diào)用中做瞪。