如何用大写字母替换特定字符? [英] How can I replace a particular character with its upper-case counterpart?
问题描述
考虑以下字符串
String = 这是为了测试.我是 perl 新手!请帮忙.你能帮忙吗?我希望如此."
在.
或?
或!
之后的上述字符串中,下一个字符应为大写.我该怎么做?
In the above string after .
or ?
or !
the next character should be in upper case. how can I do that?
我正在逐行读取文本文件,我需要将修改后的数据写入另一个文件.
I'm reading from text file line by line and I need to write modified data to another file.
您的帮助将不胜感激.
推荐答案
你可以使用正则表达式试试这个:
you could use a regular expression try this:
my $s = "...";
$s =~ s/([\.\?!]\s*[a-z])/uc($1)/ge; # of course $1 , thanks to plusplus
g-flag 搜索所有匹配项,e-flag 执行 uc 将字母转换为大写
the g-flag searches for all matches and the e-flag executes uc to convert the letter to uppercase
说明:
- 使用 [.\?!] 搜索标点符号
- \s* 用于标记和下一个单词的第一个字母之间的空格和
- [a-z] 匹配单个字母(在本例中为下一个单词的第一个字母
上面提到的正则表达式使用这些模式搜索标点符号后跟(可选)空格和字母的每个出现,并将其替换为 uc 的结果(将匹配转换为大写).
the regular expression mentioned above searches with these patterns for every appearance of a punctuation mark followed by (optional) whitespaces and a letter and replaces it with the result of uc (which converts the match to uppercase).
例如:
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"然后替换,所以打印结果为:
will find ". i", "! P", ". c" and "? i" and replaces then, so the printed result is:
this is for test. I'm new to perl! Please help. Can u help? I hope so.
这篇关于如何用大写字母替换特定字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!