【问题标题】:How to interpolate variables into Perl 6 regex character class?如何将变量插入 Perl 6 正则表达式字符类?
【发布时间】:2017-11-04 18:09:58
【问题描述】:

我想把一个单词的所有辅音都变成大写:

> my $word = 'camelia'
camelia
> $word ~~ s:g/<-[aeiou]>/{$/.uc}/
(「c」 「m」 「l」)
> $word
CaMeLia

为了使代码更通用,我将所有辅音的列表存储在一个字符串变量中

my $vowels = 'aeiou';

或在数组中

my @vowels = $vowels.comb;

如何用$vowels@vowels变量解决原来的问题?

【问题讨论】:

    标签: raku


    【解决方案1】:

    也许trans 方法比subst 子或运算符更合适。

    试试这个:

    my $word = "camelia";
    my @consonants = keys ("a".."z") (-) <a e i o u>;
    say $word.trans(@consonants => @consonants>>.uc);
    # => CaMeLia
    

    【讨论】:

    • 谢谢!在这种情况下确实容易得多。我是否正确理解 (-) 将两个列表强制为集合,keys 使集合减法的结果成为列表?
    • 是的,就是这样。可以通过多种方式做到这一点,但这是我能想到的最简单的方法:)
    【解决方案2】:

    moritz's explanation的帮助下,解决方法如下:

    my constant $vowels = 'aeiou';
    my regex consonants {
        <{
           "<-[$vowels]>"
         }>
    }
    
    my $word = 'camelia';
    $word ~~ s:g/<consonants>/{$/.uc}/;
    say $word;  # CaMeLia
    

    【讨论】:

    • 这也可以内联完成:/&lt;{"&lt;-[$vowels]&gt;"}&gt;/Try it online
    【解决方案3】:

    您可以使用&lt;!before …&gt; 以及&lt;{…}&gt;. 来实际捕捉角色。

    my $word = 'camelia';
    $word ~~ s:g/
    
      <!before         # negated lookahead
        <{             # use result as Regex code
          $vowel.comb  # the vowels as individual characters
        }>
      >
    
      .                # any character (that doesn't match the lookahead)
    
    /{$/.uc}/;
    say $word;         # CaMeLia
    

    您可以用@vowels 取消&lt;{…}&gt;

    我认为意识到你可以使用.subst也很重要

    my $word = 'camelia';
    say $word.subst( :g, /<!before @vowels>./, *.uc ); # CaMeLia
    say $word;                                         # camelia
    

    我建议将正则表达式存储在变量中。

    my $word = 'camelia'
    my $vowel-regex = /<-[aeiou]>/;
    
    say $word.subst( :g, $vowel-regex, *.uc ); # CaMeLia
    
    $word ~~ s:g/<$vowel-regex>/{$/.uc}/;
    say $word                                  # CaMeLia
    

    【讨论】:

    • 感谢您的完美回答! (虽然我认为解决方案会更容易——在我陷入当前程序后,我浪费了很多时间试图找到它)​​。在多次阅读您的答案,然后用不同的更改测试代码 sn-ps 之后,我终于更好地理解了前瞻和后瞻的工作原理。至于最后一个解决方案,我的问题仍然存在:如何将@vowels$vowels 插入$vowel-regex。在我的程序中,最好不要将此类信息“硬编码”。
    • 终于,我明白了! my $vowel-regex = "/&lt;-[$vowels]&gt;/".EVAL;再次感谢您的解释!
    • @EugeneBarsky 您可以进行在线评估:my $match-consonant-rx = /&lt;{ "&lt;-[$vowels]&gt;" }&gt;/;
    猜你喜欢
    • 2017-04-14
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    相关资源
    最近更新 更多