【问题标题】:How can I replace a particular character with its upper-case counterpart?如何用大写对应字符替换特定字符?
【发布时间】:2011-10-13 12:15:06
【问题描述】:

考虑下面的字符串

String = "这是为了测试。我是 perl 新手!请帮忙。你能帮忙吗?我希望如此。"

.?! 之后的上述字符串中,下一个字符应为大写。我该怎么做?

我正在逐行读取文本文件,我需要将修改后的数据写入另一个文件。

您的帮助将不胜感激。

【问题讨论】:

    标签: perl


    【解决方案1】:

    你可以使用正则表达式 试试这个:

    my $s = "...";
    $s =~ s/([\.\?!]\s*[a-z])/uc($1)/ge; # of course $1 , thanks to plusplus
    

    g-flag 搜索所有匹配项,e-flag 执行 uc 将字母转换为大写

    解释:

    • 使用 [.\?!] 搜索标点符号
    • \s* 用于标记和下一个单词的第一个字母之间的空格,并且
    • [a-z] 匹配单个字母(在这种情况下是下一个单词的第一个)

    上面提到的正则表达式使用这些模式搜索每个出现的标点符号,后跟(可选)空格和一个字母,并将其替换为 uc 的结果(将匹配转换为大写)。

    例如:

    my $s = "this is for test. i'm new to perl! Please help. can u help? i hope so.";
    $s =~ s/([\.\?!]\s*[a-z])/uc(&1)/ge;
    print $s;
    

    会找到“.i”、“!p”、“.c”和“?i”并替换then,所以打印结果是:

    this is for test. I'm new to perl! Please help. Can u help? I hope so.
    

    【讨论】:

    • 感谢您的重播,但我不明白,请您举个例子。
    • uc()中应该是$1而不是&1
    • 你自己引用的帮助测试中暗示了:-)
    • 不需要使用/e和uc(),使用\u,如:s/([.?!]\s*)(\w)/$1\u$2/g
    • 如何在替换部分内添加空格? `uc($1)` 替换为uc($1),空格被忽略
    【解决方案2】:

    您可以使用替换运算符s///

       $string =~ s/([.?!]\s*\S)/ uc($1) /ge;
    

    【讨论】:

    • 这个答案可能会有一些评论,特别是考虑到 OP 是 Perl 的新手。
    • @nathan OP 实际上并没有说他是 perl 新手,只是他的示例字符串中的文本。
    • @TLP:他写在示例文本中。
    • 嘿伙计们,如果你在谈论我。是的,正如我在 det 示例中所说,我是 perl 新手。
    • @banadishrs 我只是向 Nathan 指出,您的陈述存在固有的歧义。这与您真正的意思无关。 ;)
    【解决方案3】:

    这是split 解决方案:

    $str = "this is for test. im new to perl! Please help. can u help? i hope so."; 
    say join "", map ucfirst, split /([?!.]\s*)/, $str;
    

    如果您所做的只是打印到一个新文件,则无需将字符串加入备份。例如

    while ($line = <$input>) {
        print $output map ucfirst, split /([?!.]\s*)/, $line;
    }
    

    【讨论】:

    • 你需要正则表达式来拆分;)
    • @Hachi 哦,我明白你的意思了。是的,我想我把球丢在那里了。
    【解决方案4】:

    编辑 - 完全误读了这个问题,以为您只是出于某种原因要求将is 大写,如有任何混淆,我们深表歉意!

    到目前为止,您可以查看正则表达式和替换运算符(s///)。没有人提到\b(单词边界)字符,这可能有助于找到单个is - 否则您将不得不继续添加您找到的标点字符到字符类匹配( [ ... ])。

    例如

    my $x = "this is for test. i'm new to perl! Please help. can u help? i hope so. ".
           \"i want it to work!\". Dave, Bob, Henry viii and i are friends. foo i bar.";
    
    $x =~ s/\bi\b/I/g;  # or could use the capture () and uc($1) in eugene's answer
    

    给予:

    # this is for test. I'm new to perl! Please help. can u help? I hope so. 
    # "I want it to work!". Dave, Bob, Henry viii and I are friends. foo I bar.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2023-04-05
      • 2023-03-09
      相关资源
      最近更新 更多